douhui3760 2016-02-25 18:32
浏览 48
已采纳

没有找到MySQL行,但它就在那里

I'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.

$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
        while($row = $result->fetch_row())
        {
            echo $row[0];    
        }
        $result->close();
}
else
        echo "No results for username ".$username." for character ".$characterName.".";

And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?

This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.

<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];

$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");

if(mysqli_connect_errno())
{
        printf("Connect failed: %s
", mysqli_connect_error());
        exit();
}

$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";

if($result = $mysqli->query($query))
{
        while($row = $result->fetch_row())
        {
            echo $row[0];    
        }

        $result->close();
}
else
        echo "No results for username ".$username." for character ".$characterName.".";

$mysqli->close();
?>
  • 写回答

2条回答 默认 最新

  • dongyongkui6329 2016-02-25 19:00
    关注

    It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.

    Connecting to a database using the MySQLi API requires 4 parameters:

    If your password isn't required, you still need an (empty) parameter for it.

    I.e.: $mysqli = new mysqli("host","user", "", "db");

    Plus, as noted.

    Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.


    Footnotes:

    As stated in the original post. Strings require to be quoted in values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100