检查行是否存在,否则创建一行

时间:2014-11-26 07:05:28

标签: php mysql

动机:如果不存在具有相同数据的数据,我只想创建指定数据的行。 到目前为止我尝试过的是 -

CODE:

<?php
if(empty($_GET['a'])) {$xyz ="new";} else{$xyz=$_GET['a'];}
$servername = "mysql.soemwhere.com";
$username = "u130204422_acb";
$password = "YES-I-KNOW";
$dbname = "u130204422_acb";


$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$output ="SELECT * FROM trailers
WHERE url='$xyz' LIMIT 1";
$result = mysqli_query($conn,$output);
while($row = mysqli_fetch_array($result)) {
 $pid=$row["title"];
echo $pid;}
if (mysqli_num_rows($result) > 0) {echo 'yes';}
else{
$msql = "INSERT INTO `trailers`(`url`,`title`) VALUES ('$xyz','dekhlia')";
if ($conn->query($msql) === TRUE) {
    echo "New record created successfully. Refrsh the page and it will echo dekhlia";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;}
echo "hehe";
$conn->close();} 
?>

我无法弄清楚为什么这段代码正在工作。

1 个答案:

答案 0 :(得分:2)

您不必要在SQL字符串中添加连接。

它是刺痛的一部分,所以,将它移除。

更改

$output ="SELECT * FROM trailers
WHERE url='.$xyz.' LIMIT 1";

要:

$output ="SELECT * FROM trailers
WHERE url='$xyz' LIMIT 1";