更新mysql表中的数据

时间:2013-09-24 16:25:20

标签: php mysql sql increment

我试图看看keyWord是否已经存在于表searchWords中。如果确实如此,则国家增加1。如果表中不存在,那么我使用了INSERT。问题是,传递给站点的keyWord没有存储在DB中。另一个大问题是国家没有增加。是因为if声明吗?或者是while循环?

<?php
date_default_timezone_set('Asia/Manila');
$today = date('m-d-Y');
echo $today;
$urltopost = "http://opac.usls.edu.ph/TLCScripts/interpac.dll?Search";
$datatopost = "FormId=0&Config=pac&LimitsId=0&StartIndex=0&SearchField=7&SearchType=1&ItemsPerPage=20&SearchData=$_POST[keyWord]";
$ch = curl_init ($urltopost);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $datatopost);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$returndata = curl_exec ($ch);
echo $returndata;
$con=mysqli_connect("...","...","...","...")or die ('Error: ' . mysql_error());
$sql= "SELECT * FROM searchedWords";
$result= mysqli_query($con,$sql);


 while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{            
        if($row['keyWord']==$_POST[keyWord])
         {
         $upD="UPDATE searchedWords SET countr = countr + 1 WHERE keyWord = '".$row['keyWord']."'";
          while (!mysqli_query($con,$upD))
          {
           die('Error: ' . mysqli_error($con));
           }
         }
        else
        {
         $insertIn="INSERT INTO `searchedWords`( `keyWord`, `countr`) values ('$_POST[keyWord]',1)";
      while (!mysqli_query($con,$insertIn))
          {
          die('Error: ' . mysqli_error($con));
          }
        } 
}
?>

感谢那些可以帮助我的人。

2 个答案:

答案 0 :(得分:0)

在循环中运行sql查询真的很糟糕。尝试使用此类查询来更新所有现有关键字:

    $keyword = htmlspecialchars($_POST['keyWord']);

    UPDATE searchedWords SET countr = countr + 1 WHERE keyWord = '".$keyword."'";

不再循环!

使用数据库更安全有效地工作,请查看http://php.net/manual/en/pdo.prepared-statements.php

答案 1 :(得分:0)

为什么让事情变得复杂......尝试简单的方法

$KeyWord = $_POST['keyWord']; //Do not forget to sanitize this for security
$sql= "SELECT * FROM searchedWords WHERE keyWord='$KeyWord'";
$result= mysqli_query($con,$sql);
$count= mysqli_num_rows($result);

if($count) {
$upD="UPDATE searchedWords SET countr = countr + 1 WHERE keyWord = '$keyWord'";
mysqli_query($con,$upD);
} else {
$insertIn="INSERT INTO `searchedWords`( `keyWord`, `countr`) values ('$keyWord',1)";
mysqli_query($con,$insertIn); }