php - 我的页面出现mysql错误

标签 php mysql sql

我需要帮助解决连接到我的数据库并获得我想要的东西的问题。我以前用 php 编程过,从来没有遇到过这个问题。我收到此错误消息。

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'character WHERE username = David' at line 1

这是我的代码。

    <?php
        $con = mysqli_connect("localhost","root","","thespianassistant");
        $username = $_GET['username'];
        $query = "SELECT * FROM `character` WHERE `username` = $username";
        $data = mysqli_query($con, $query) or die(mysqli_error($con));
    ?>

最佳答案

这是您使用 PDO 的代码端口,也许您会感兴趣,不要使用旧的 mysql_* 函数。

<?php
//connect to database using PDO
try{
    $db = new PDO('mysql:host=localhost;dbname=thespianassistant', 'root', 'you_should_set_a_password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    //Query the db & fetch result
    $sql = "SELECT * 
            FROM `character` 
            WHERE username = :username";

    $query = $db->prepare($sql);
    $query->execute(array(':username' => $_GET['username']));

    $result = $query->fetchAll(PDO::FETCH_ASSOC);

}catch(PDOException $e){
    die($e->getMessage());
}

//do something with result
if(!empty($result)){
    echo '<pre>'.print_r($result, true).'</pre>';
}else{
    //no character found
}

关于php - 我的页面出现mysql错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23256597/

相关文章:

mysql - 如何使用单个查询查询多个表

php - 使用 mysql if 语句更改按钮按下时的值

SQL Server : Change current database via variable

php - 如何在 Doctrine 的 Mongodb ODM 中使用正则表达式?

在 php-cli 中重新加载 php.ini

php - 显示 Apache 当前正在运行的 php 脚本

c# - 将比较运算符作为参数传递给 SQL 查询

php - Laravel/Eloquent 5 whereBetween 没有按预期工作

mysql - 通过减去日期之间的值来更新列

sql - 如何合并行并在 SQL 表中添加列?