0

I am trying to see if keyWord already exists in table searchedWords. If it does, then the countr increases by one. If it does not exists in the table, then I used INSERT. The problem is, the keyWord being passed to the site is not stored in the DB. The other BIG problem is that the countr does not add at. Is it because of the if statement? Or is it the while loop?

<?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));
          }
        } 
}
?>

Thank you to those who can help me out.

4

2 回答 2

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); }
于 2013-09-24T16:51:23.020 回答
0

在循环中运行 sql 查询是非常糟糕的做法。尝试使用这样的查询来更新所有现有的关键字:

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

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

没有更多的循环!

为了更安全、更高效地使用数据库,请查看http://php.net/manual/en/pdo.prepared-statements.php

于 2013-09-24T16:32:54.380 回答