MySqli Php似乎没有“排序依据" [英] Doesn't seem to 'order by' for MySqli Php

查看:47
本文介绍了MySqli Php似乎没有“排序依据"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP的MySqli中,我的Order by遇到了麻烦.它是bind_param不能工作的原因还是其他原因.我不确定在这里忘记什么,只是不想接受我的约束.预先感谢.

I'm having troubles with my Order by in MySqli in PHP. It either the bind_param not working for or something else. I not sure what I'm forgetting here, it just doesn't want to accept my bind. Thanks in Advance.

 @ $db = new mysqli('localhost', 'root', '', 'books');
    // if mysqli_connect_errno() is set, we did not successfully connect. Here we deal with the error.
    if (mysqli_connect_errno()) {
        echo 'Error: Could not connect to database.  Please try again later.</body></html>';
        die();
    }
    $sortOrder = 'title';

    $query = "SELECT ISBN, Author, Title, Price FROM books ORDER BY ?";
    $stmt = $db->prepare($query);
    $stmt->bind_param('s', $sortOrder);

    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($isbn, $author, $title, $price);

    echo "<p>Number of books found: " . $stmt->num_rows . "</p>";

    $counter = 0;
    if ($stmt->num_rows > 0) {
        while ($stmt->fetch()) {
            $newBook = new book($isbn, $author, $title, $price);
            $bookList[$counter] = $newBook;
            $counter++;
        }
    } else {
        //Nothing
    }
    $stmt->free_result();
    $db->close();

推荐答案

您不能绑定标识符(表/列),只能绑定值.使用白名单检查该值是否为已知对中的一个,然后将其传递.

You can't bind identifiers (tables/columns), you can only bind values. Use a whitelist to check the value is one of a known pair then pass it in if it is.

if(in_array($column, array('title', 'possible_other_column'))) {
     $query = "SELECT ISBN, Author, Title, Price FROM books ORDER BY $column";
     $stmt = $db->prepare($query);
     $stmt->execute();
} else {
     echo 'Column is not a valid name please select a valid column';
     //or whatever behavior you want to happen, maybe just use a default column

这篇关于MySqli Php似乎没有“排序依据"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆