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

时间:2018-09-12 19:10:02

标签: php mysql sql

在阅读了stackoverflow几个小时并尝试了各种建议之后,我似乎无法获得一个简单的sql语句。

我正在将最新的XAMPP本地主机与Apache一起用于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 )

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法吗:

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

另外,我认为您应该这样:

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

答案 1 :(得分: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();
相关问题