Php 使用select*和准备好的语句和查询的mysqli

Php 使用select*和准备好的语句和查询的mysqli,php,mysql,select,mysqli,Php,Mysql,Select,Mysqli,我一直在努力寻找我的确切情况。我想了解为什么这不起作用,同时我想确保这种逻辑在注入黑客攻击中更安全。我知道没有什么是100%安全的。以下代码不起作用: $query= mysqli_prepare($con,"SELECT * FROM *table* WHERE Resource = ? AND WorkDate >= ? AND WorkDate <= ? ORDER BY WorkDate, StartTime" ); mysqli_stmt_bind_param(

我一直在努力寻找我的确切情况。我想了解为什么这不起作用,同时我想确保这种逻辑在注入黑客攻击中更安全。我知道没有什么是100%安全的。以下代码不起作用:

$query= mysqli_prepare($con,"SELECT * FROM *table*
    WHERE Resource = ? AND WorkDate >= ? AND WorkDate <= ? ORDER BY WorkDate, StartTime" );


mysqli_stmt_bind_param($query, "sss", $resource, $from, $to);
mysqli_execute($query);

if (!mysqli_stmt_execute($query))
{
    die('Error: ' . mysqli_error());
}
mysqli_stmt_store_result($query);

mysqli_stmt_fetch($query);

$result= mysqli_query($con,$query, MYSQLI_STORE_RESULT); // or die("Could not get results: ".mysqli_error()); 
while($rows=mysqli_fetch_array($result)){<fill in table>
此代码在$result行中消失。我已经对查询和所有变量进行了var_转储。当我使用var_dump查询时,它会正确地告诉我受影响的行。所以对我来说,这意味着准备好的声明是有效的。但是,当我试图运行查询时,我可以获取它以在屏幕上输出数据


现在它可以用于mysql,但我正在尝试将其转换为mysqli以避免注入。最初整个sql语句都准备好了,但现在使用prepared语句来避免这种情况。

您需要理解prepared语句和常规查询之间的区别。一旦您以准备好的语句开始,您必须以这种方式运行,直到结束,除非您通过mysqli_stmt::get_result存储结果,然后您可以使用mysqli::fetch_assoc和类似的函数-这在本答案中没有涉及,请参阅手册以获取示例

假设代码中有*table*,我认为这是错误的。请相应地更改所选列和所选表下面查询的前两行

为bind_result指定的变量数量必须与您在查询中选择的列数量完全匹配,这一点很重要。这些变量将为每个迭代保存列的值

这里有一个起点来引导你朝着正确的方向前进。在querystring prepare和results bind_result的绑定中相应地更改column1到column3的名称。如前所述,这是一对一的比赛。您还必须相应地更改表的名称,myTableName当前只是一个占位符,就像column1到column3一样

手册也是阅读示例的好地方


错误消息是什么?您已经设置了错误报告级别E_ALL,检查日志或显示错误?来自*table*的是您的实际代码吗?另外$query是mysqli语句对象,您不能将其传递给mysqli_query。有用的通用错误跟踪特定于mysqli Add ini set'display_errors',1;ini_设置“日志错误”,1;错误报告全部;mysqli_REPORT mysqli_REPORT_ERROR | mysqli_REPORT_STRICT;到脚本的顶部。这将强制任何mysqli_uuu错误生成一个您可以在浏览器上看到的异常,其他错误也将在浏览器上看到。表只是一个占位符。本来应该把它斜体化。
// Prepare the query
$stmt = $con->prepare("SELECT column1, column2, column3 
                       FROM myTableName
                       WHERE Resource = ? 
                         AND WorkDate >= ? 
                         AND WorkDate <= ? 
                       ORDER BY WorkDate, StartTime");
if (!$stmt) {
    // Check for errors, if the prepare failed, it will return 'false'
    echo "An unexpected error occurred, check the logs.";
    error_log($con->error);
    exit;
}

// Bind the parameters (?)  in the query and execute it
$stmt->bind_param("sss", $resource, $from, $to);
if (!$stmt->execute()) {
    echo "An unexpected error occurred, check the logs.";
    error_log($stmt->error);
    $stmt->close();
    exit;
}

// Bind the results of each column into a variable
$stmt->bind_result($column1, $column2, $column3);

// In this loop we use the variables that we bound in the function bind_result above
// In this example, we simply print their values
while ($stmt->fetch()) {
    echo "$column1 -- $column2 -- $column3";
}

// Close the statement after use!
$stmt->close();