PHP中的SQL查询错误

Posted

技术标签:

【中文标题】PHP中的SQL查询错误【英文标题】:SQL Query error in PHP 【发布时间】:2012-10-06 17:38:01 【问题描述】:

这是自助餐厅的代码,这是登录名。

<?php

$userna = 'root';
$paso = '';
$mach = 'localhost';
$db ='cafeteria';

session_start();

// GET PAGES RECORD FROM LOG TABLE: *********| Only the first time though:
if (isset($_SESSION['log']) != 'logging')

    //  Here, just creating a string:
    $pages_record = "";
    $insert_query = '';
    //      Get saved pages from the database:
    $connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Error in log-page script: AB-1 - query: $insert_query." . mysqli_error($connection));
    mysqli_select_db($connection,'cafeteria');

    //      Query string to pull all pages from table record:
    $get_pages_query = "select * from log-page";

    //      Query the database, and save result:
    $query_pages_result = mysqli_query($connection, $get_pages_query);

    //      Check number of results returned:
    $num_of_results = '';
    $num_of_results = mysql_num_rows($query_pages_result);
    if ($num_of_results > 0)
    
        // Loop through the result array: Each time, one row, and then the next one ...
        for ($row = 0; $row < $num_of_results; $row++ )
        
            // Getting one row:
            $get_row = mysqli_fetch_array($query_pages_result);
            // Extracting just the page name from the row:
            $one_page = substr($get_row["page"],strripos($get_row["page"],"/") + 1);
            // Adding this page name to the string created previously:
            if ($row == 0)
            
                $pages_record .= $one_page;
            
            else 
            
                $pages_record .= ",".$one_page;
                       
        

        // Once all pages have been read and saved to the string
        // now we save it to the session:
        $_SESSION['logpages'] = $pages_record;
        $_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
    
    else 
    
        // There are no pages in the table:
        $_SESSION['logpages'] = "";
        $_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
    


// Check if page is already in session list.
$pages_array = array();
if (strlen(isset($_SESSION['logpages'])) > 0 )

    // string variable that holds all pages separated by commas:
    $pages_string =  $_SESSION['logpages'];

    // creating an Array to hold all pages already logged in server:
    if (strstr($pages_string, ","))
    
        $pages_array = explode(",", $pages_string);
    
    else // just means there's only one page in the record
    
        // so, we push it inside the array.
        array_push($pages_array, $pages_string);
    

    // current page: [ We are extracting only the page, not the entire url, Exmp: login.php ]
    $current_page = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);

    // Check if current_page is in the array already:
    if (!in_array($current_page, $pages_array))
    
        // IF is NOT in the array, then add it:
        array_push($pages_array, $current_page);

        // Add it to the Session variable too:
        $pages_string = implode(",", $pages_array);

        // Re-save it to SESSION:
        $_SESSION['logpages'] = $pages_string;

        // Now, add it to the database table "log-page""
        $connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
        mysqli_select_db($connection,'cafeteria');

        // Query to insert page description into the table:
        // [ date - time - page - user ]
        $insert_query = "INSERT INTO log-page 
            (`date`, `time`, `page`, `user`) VALUES 
            ('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')"; 
            mysqli_select_db($connection,'cafeteria');

        // INSERTING INTO DATABASE TABLE:
        mysqli_query($connection, $insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
        // Done!
    
    else 
    
        // IF it IS in the list, just SKIP.
    

else 

    // means, that there are absolutely no pages saved in the database, basically this is the first log:
    $_SESSION['logpages'] = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);    

    // Now, add it to the database table "log-page""
    $connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
    mysqli_select_db($connection,'cafeteria');

    // Query to insert page description into the table:
    // [ date - time - page - user ]
    $insert_query = "INSERT INTO log-page 
        (date, time, page, user) VALUES 
        ('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')"; 
    mysqli_select_db($connection,'cafeteria');
    // INSERTING INTO DATABASE TABLE:
    mysqli_query($connection,$insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
    // Done!    


?>

但是现在我收到了这个错误:

日志页面脚本错误:AB-2 - 查询:INSERT INTO 日志页面 (date, time, page, user) 值 ('2012-10-16', '16:58:44', '/caf/pages/index.php', ''). 你的 SQL 语法有错误; 检查与您的 MySQL 服务器版本相对应的手册 在 '-page 附近使用正确的语法 (date, time, page, user) 值('2012-10-16','16:58:44' 在第 1 行

我正在使用 Xampp 1.8.1 PHP:5.4.7。它不允许我以管理员身份或收银员身份登录

【问题讨论】:

尝试`date` 而不是date。使用引号。日期是一个规范。 MYSQL 中的单词。 您的用户申请是否允许 null ?而对于xampp,你是否更改了root密码并且无法登录phpmyadmin? 不,它不允许用户为空。根密码为空 【参考方案1】:

用这样的反引号将表名括起来(省略查询的其余部分):

$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) ... "; 

否则 MySQL 将尝试将 - 解释为减号,在这种情况下会失败。

编辑

在显示的最后一个插入中,列名也应该用反引号括起来:

$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) VALUES ...";

【讨论】:

是的,破折号在列名中无效,因此必须用反引号括起来…… 我做到了,现在我遇到了这个问题警告:mysql_num_rows() 期望参数 1 是资源,在第 47 行的 C:\xampp\htdocs\caf\pages\log.php 中给出的布尔值 @jjumar 在另一个查询中看起来同样的错误:在log_page 周围添加反引号:$get_pages_query = "select * from log-page"; @jjumar 在查询之后添加这样的语句,为您带来相应mysql_num_rows()中的参数:if ( mysql_error() ) echo mysql_error(); 。然后查看错误消息并采取相应措施。不过,我不会在 cmets 中调试你所有的脚本。 @Sirko 现在的问题出在 mysql_num_rows 的参数上......似乎 $query_pages_result 没有给我一个布尔或数字结果【参考方案2】:

尝试转义字段名

(`date`, `time`, `page`, `user`)

【讨论】:

【参考方案3】:

自从我查看 mySql 文档以来已经有一段时间了,但它似乎在抱怨表名“log-page”。尝试引用该表名。

【讨论】:

我做到了,现在我遇到了这个问题警告:mysql_num_rows() 期望参数 1 是资源,在第 47 行的 C:\xampp\htdocs\caf\pages\log.php 中给出的布尔值

以上是关于PHP中的SQL查询错误的主要内容,如果未能解决你的问题,请参考以下文章

在 SQL 中有效但在 PHP 中无效的查询

sql的一般查询语句(增删改查中的查)

“SQLSTATE[HY000]: 一般错误” - 一条语句中有多个 SQL 查询

将sql查询存储在列表中时PHP内存耗尽

PHP,MY SQL错误查询[重复]

为啥我在 PHP 中的 SQL 查询失败?