PHP - MySQL SELECT和证明

时间:2014-07-20 03:15:43

标签: php mysql sql select insert

我想从数据库中读取一些东西,然后用PHP写一些东西。

以下是代码:

$id = mysqli_real_escape_string($con, $_SESSION['id']);
$title = mysqli_real_escape_string($con, $_SESSION['title']);
$link = mysqli_real_escape_string($con, $_SESSION['link']);
$count = 0;

$sql_write = "INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id', '$count')";
$sql_read = "SELECT count FROM recent WHERE sc_stream = " . $id;

$data = myql_query($con, $sql_read);
$info = myql_fetch_array($data);

while($info = mysql_fetch_array($data)) {
    if(isset($info['count']) {
        $count = $info['count'];
    }
}

if(isset($id, $title, $link)) {
    if (!mysqli_query($con,$sql_write)) {
      die('Error: ' . mysqli_error($con));
    }
}

当我取消注释$data$info变量时,它会写入数据(count = 0)。但是当它没有被注释时,它什么也没做。

1 个答案:

答案 0 :(得分:1)

让我们从错误开始:

  • 没有名为myql的库。我压缩你的意思是mysqlmysqli
  • 现在注意:由于库已被折旧,您应该停止使用mysql_*函数。
  • 使用PDOMySQLi

这整段代码都是多余的:

$info = myql_fetch_array($data);

while($info = mysql_fetch_array($data)) {
    if(isset($info['count']) {
        $count = $info['count'];
    }
}

现在我要说你面临的主要错误是你的逻辑顺序错误。 这就是你现在正在做的事情:

  • 清理变量(清理)。
  • 构建SQL查询。
  • 运行查询。
  • 检查是否设置了变量。

你应该做的是:

// set variables
$id = mysqli_real_escape_string($con, $_SESSION['id']);
$title = mysqli_real_escape_string($con, $_SESSION['title']);
$link = mysqli_real_escape_string($con, $_SESSION['link']);
$count = 0;
// make sure set and not empty
// Should probably only really make sure that the variables are not empty.
if(isset($id, $title, $link) && !empty($id) && !empty($title) && !empty($link)) {
// build query
$sql_read = "SELECT count FROM recent WHERE sc_stream = " . $id;
$data = mysqli_query($con, $sql_read);

if(!$data) {
    // read query failed.
    die('Error: ' . mysqli_error($con));
} else {
    // fetch and update count
    while($info = mysqli_fetch_array($data)) {
        if(isset($info['count']) {
            // set count
            $count = $info['count'];
        }
    }       
    $sql_write = "INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id', '$count')";

    // run the write query
    if (!mysqli_query($con,$sql_write)) {
        // write query failed
        die('Error: ' . mysqli_error($con));
    } else {
        // write query succeeded, do what you need to here.  
    }
}

我已经注释了每个代码部分对注释的作用,如上所示。

有任何问题,请问!

另外如果您不介意我问,为什么要清理会话变量?它们是通过用户输入设置的吗?