php - 简单: Passing PHP var into SQL fails MySqli query

标签 php mysql sql

在阅读了 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 )

最佳答案

你能尝试这样的事情吗:

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

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

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

关于php - 简单: Passing PHP var into SQL fails MySqli query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52301890/

相关文章:

php - 为后期静态绑定(bind)复制函数

php - Angular - 存储复选框值并显示它们

php - 对我自己的站点执行字典攻击

php - MySQL : LEFT JOIN for 4 tables which are connected to each other

用于 Google BigQuery 的 SQL 查询来计算 session 和网页浏览量

sql - 我可以在搜索的 case sql 语句中有多个 bool 表达式吗?

php - 在 Laravel 中访问 php 数组

java - 从服务器发送数据的最佳方式

sql - 同一张表,1字段转2字段查询

sql - 如何在选择查询中比较多列与多字段数组?