-3

我对 php 和 MySQL 有点陌生。当我调用下面的函数时,我正在阅读教程并收到上述消息。

<?php
function get_subject_by_id($subject_id){
    global $connection;
    $query = "SELECT * FROM subjects WHERE id=" . $subject_id . "LIMIT 1";
    $result_set = mysql_query($query, $connection);
        confirm_query($result_set);
    //if no rowes are returned, fetch array will return false
    if ($subject = mysql_fetch_array($result_set)) {
        return $subject;
    } else { 
        return NULL;
    }
}
?>
4

2 回答 2

7

$query = "SELECT * FROM subjects WHERE id=" . $subject_id . "LIMIT 1";

应该

$query = "SELECT * FROM subjects WHERE id=" . $subject_id . " LIMIT 1";

注意前面的空格LIMIT 1

但是我们仍然不知道您的问题是什么,因为您没有指定。

于 2012-10-29T21:31:06.433 回答
0

这是相同代码的 PDO 版本,以及一些关于 PDO 的好读物

设置您的连接,然后您可以使用 PDO 更安全的查询功能,如下所示:

function get_subject_by_id($subject_id){
    $host = 'localhost';
    $dbname = 'name_of_database';
    $user = 'user_name';
    $pass = 'User_password';
    try{
        $DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
    }catch(PDOException $e){  
        echo $e->getMessage();  
    }
    $query = "SELECT * FROM subjects WHERE id=? LIMIT 1";
    $result_set = $DB->prepare($query);
    //Include the variables to pass with the query
    $result_set->execute(array($subject_id));
    //You should modify this function to use PDO as well
    confirm_query($result_set);
    //if no rowes are returned, fetch array will return false
    if ($result_set->rowCount()) {
        return $subject;
    } else { 
        return NULL;
    }
}

这里有一些阅读:

http://www.php.net/manual/en/book.pdo.php

于 2012-10-29T21:42:57.310 回答