简单:将PHP var传递给SQL会失败MySqli查询

问题描述 投票:0回答:2

通过stackoverflow阅读几个小时并尝试各种建议后,我似乎无法得到一个简单的SQL语句工作。

我正在使用最新的XAMPP localhost和Apache for PHP和MySQL。

- - - - - - - - - -表 - - - - - - - -

id |名字|交易|

1 |大卫| 1234V |

在PhpMyAdmin中,以下非变量sql返回1行。但是,变量sql返回非功能性资源。

我已经尝试了对$ mysqli-> query()的sql语句和语法的各种重新安排;

我错过了php.ini中的东西吗?

$text = "here we have a long string of text with transaction ID: 1234V and some other stuff mixed in here.";

//lets cutup the string and only extract the transaction id
$array = explode("transaction ID: ", $text);

if (isset($array[1]))
    $array = explode("and", $array[1]);

$variable = $array[0]; //$array[0] = '1234V ';
$trans = "SELECT * FROM `name` WHERE `transaction` = '$variable';";

if($statement = $mysqli->prepare("$trans")){
    $statement->execute();
    $statement->bind_result($id,$name,$transaction);

    while ($statement->fetch()) {
        printf("%s %s\n",$id,$name,$transaction);
    }

    $statement->close();
}
$mysqli->close();
die();

这个带有$ variable的新代码打印了这个:

$trans = "SELECT * FROM `name` WHERE `transaction` = '$variable';";
mysqli_result 

Object ( [current_field] => 0 [field_count] => 3 [lengths] => [num_rows] => 0 [type] => 0 )

并且硬编码的新代码打印出来:

$trans = "SELECT * FROM `name` WHERE `transaction` = '1234V ';";
mysqli_result

Object ( [current_field] => 0 [field_count] => 3 [lengths] => [num_rows] => 1 [type] => 0 )
php mysql sql
2个回答
0
投票

你能尝试这样的事吗:

$trans = "SELECT * FROM `name` WHERE `transaction` = ?";

另外,我认为你应该试试这个:

$statement = $mysqli->prepare($trans);
$statement->bind_param("s", $passed[variable]);
$statement->execute();
if(...

0
投票
$trans = "SELECT id, name, transaction FROM `name` WHERE `transaction` = ? ;";

if($statement = $mysqli->prepare($trans)){
    echo 'Let\'s check we are in? '.$passed['variable']."\n";
    $statement->bind_param("s", $passed['variable']);

    $statement->execute();
    $statement->bind_result($id, $name, $transaction);

    while ($statement->fetch()) {
        printf("FETCHED: %s %s %s\n", $id, $name, $transaction);
    }
    echo "Let's check we are out? \n";
    $statement->close();
} else {
    echo $mysqli->error;
}
$mysqli->close();
© www.soinside.com 2019 - 2024. All rights reserved.