문제

MySQLI 준비된 진술에서 널은 ''(문자열의 경우) 또는 0 (정수의 경우)으로 바뀝니다. 나는 그것을 진정한 널로 보관하고 싶습니다. 이 작업을 수행하는 방법이 있습니까?

도움이 되었습니까?

해결책

나는 이것이 오래된 스레드라는 것을 알고 있지만, 준비된 진술에 진정한 널 값을 바인딩 할 수 있습니다 (읽기 이것).

실제로 MySQLI_BIND_PARAMETER를 사용하여 NULL 값을 데이터베이스에 전달할 수 있습니다. 변수를 만들고 null 값을 변수에 저장하고 바인딩하십시오. 어쨌든 나를 위해 잘 작동합니다.

따라서 다음과 같은 것이어야합니다.

<?php
    $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

    // person is some object you have defined earlier
    $name = $person->name();
    $age = $person->age();
    $nickname = ($person->nickname() != '') ? $person->nickname() : NULL;

    // prepare the statement
    $stmt = $mysqli->prepare("INSERT INTO Name, Age, Nickname VALUES (?, ?, ?)");

    $stmt->bind_param('sis', $name, $age, $nickname);
?>

데이터베이스에 널 값을 삽입해야합니다.

다른 팁

그들이 널을 묶는 데 문제가 있기 때문에 이것을보고있는 사람에게 WHERE 진술, 해결책은 다음과 같습니다.

MySQL이 있습니다 NULL SAFE OPERATOR 사용해야합니다.

<=>

예시:

<?php
$price = NULL; // NOTE: no quotes - using php NULL
$stmt = $mysqli->prepare("SELECT id FROM product WHERE price <=> ?"); // Will select products where the price is null
$stmt->bind_param($price);
?>

댓글 PHP 문서 mysqli_stmt::bind_param 들어가는 것을 나타냅니다 NULL 쉽게 불가능했습니다.


@Creatio의 답변을 참조하십시오 : https://stackoverflow.com/a/6892491/18771


의견에 제공되는 솔루션은 준비된 진술에 대한 일부 사전 준비 작업을 수행하여 대체합니다. "?" 마커 "NULL" PHP가있는 모든 매개 변수에 대해 null 값. 그런 다음 수정 된 쿼리 문자열이 사용됩니다.

다음 기능은 사용자 의견 80119:

function preparse_prepared($sQuery, &$saParams)
{
    $nPos = 0;

    $sRetval = $sQuery;
    foreach ($saParams as $x_Key => $Param)
    {
        //if we find no more ?'s we're done then
        if (($nPos = strpos($sQuery, '?', $nPos + 1)) === false)
        {
            break;
        }

        //this test must be done second, because we need to 
        //increment offsets of $nPos for each ?.
        //we have no need to parse anything that isn't NULL.
        if (!is_null($Param))
        {
            continue;
        }


        //null value, replace this ? with NULL.
        $sRetval = substr_replace($sRetval, 'NULL', $nPos, 1);

        //unset this element now
        unset($saParams[$x_Key]);
    }
    return $sRetval;
} 

(실제로 내가했던 코딩 스타일은 아니지만 작동한다면 ...)

내 옆에 모든 매개 변수를 배열에 저장하고 Array_shift ($ myArray)에 의해 bind_param 함수로 전달합니다. Null은 그렇게 받아 들여집니다 .. S.

<?php
$mysqli=new mysqli('localhost','root','','test');
$mysqli->query("CREATE TABLE test_NULL (id int(11))");
if($query=$mysqli->prepare("insert into test_NULL VALUES(?)")){
    $query->bind_param('i',$null); //note that $null is undefined
    $query->execute();
}else{
    echo __LINE__.' '.$mysqli->error;
}
?>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top