-1

正如标题所述,我正在从旧的 MySQL_statements 切换到 PDO。我遇到了一个问题,但是在尝试查看是否'tableitem'已经存在时,如果它确实存在,我想抓取'tableitem2',如果'tableitem'不存在,我想设置'tableitem2'为 1。这是我的旧 MySQL 代码,下面我将说明什么我努力了。

$user_ip = $_SERVER['REMOTE_ADDR'];
$query = "SELECT * FROM TABLENAME WHERE user_ip='$user_ip' ";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
if (mysql_num_rows($result) )
{
  $_SESSION['stage'] = $row[1];
}
else
{
   $_SESSION['stage'] = 1;
    $strSQL2 = "INSERT INTO TABLENAME (user_ip, stage) VALUES ('$user_ip','$stage')";
     $result = mysql_query($query) or die(mysql_error());
}

以上工作,但现在我希望切换到 PDO 语句。如果我用 PDO 语句尝试过:

$user_ip = $_SERVER['REMOTE_ADDR'];

$sql = "SELECT COUNT(`stage`) FROM `TABLENAME` WHERE `user_ip` = ?";
$result = $pdo->prepare($sql); 
$result->execute(array($user_ip)); 
$number_of_rows = $result->fetchColumn();

    /* Check the number of rows that match the SELECT statement */
  if ($result->fetchColumn() > 0) {
        $_SESSION['stage'] = $row[1];
         }
  else {
      $_SESSION['stage'] = 1;
    $result = $pdo->prepare("INSERT INTO `BPGUV` (`user_ip`, `stage`) VALUES (:user_ip, :stage)";
    $result->execute(
        array(
        ':user_ip' => $user_ip,
        ':stage' => 1
        )
    );
}

非常感谢任何帮助,我已经使用 PDO 连接到数据库并且能够使用 PDO 使用 MySQL 命令,只是似乎无法将上述代码正确地转换为 PDO 语句。

4

1 回答 1

1
$user_ip = $_SERVER['REMOTE_ADDR'];
$sql = "SELECT COUNT(`stage`) FROM `TABLENAME` WHERE `user_ip` = ?";
$result = $con->prepare($sql);
$result->execute(array($user_ip)); 
$number_of_rows = $result->fetchColumn();
  /* Check the number of rows that match the SELECT statement */
  if ($number_of_rows > 0) {
        $_SESSION['stage'] = $number_of_rows;
 }
  else {
    $_SESSION['stage'] = 1;
    $result = $pdo->prepare("INSERT INTO `TABLENAME` (`user_ip`, `stage`) VALUES (:user_ip, :stage)");
    $result->execute(
        array(
        ':user_ip' => $user_ip,
        ':stage' => 1
        )
    );
}

在您的第一个查询中,您$user_ip直接在查询内部传递,而不是稍后绑定它或作为参数传递。目前,查询被视为:

SELECT COUNT(`stage`) 
FROM `TABLENAME` 
WHERE `user_ip` = 8.8.8.8

如您所知,这是错误的语法。

于 2013-10-06T08:45:12.987 回答