PHP仅向SQL数据库添加新记录

时间:2015-03-31 23:14:34

标签: php mysql sql

我只需要将新数据添加到数据库表中。我试图查询数据库,但只添加新数据。我在SQL和PHP中有点迷失。

我已将代码输入数据库但在刷新时它会再次输入相同的数据,我只希望它允许新数据:

<?php

// DATA BASE CONNECTION 

DEFINE ('DB_USERS', 'root');
DEFINE ('DB_PASS', 'root');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'sam_api');

$dbc = @mysqli_connect (DB_HOST, DB_USERS, DB_PASS, DB_NAME) OR die ('could not connect' . mysqli_connect_error());


$user_update = $items['id'];



// Check if file already exists

 $query = mysqli_query($con, "SELECT * FROM updates WHERE $user_update ='".$items['id']."'");

if(mysqli_num_rows($query) > 0){

    echo "email already exists";
}else{
    // do something
    if (!mysqli_query($con,$query))
    {
        die('Error: ' . mysqli_error($con));
    }
}


// now inserting the data form the previous page in to the database 
$q = "INSERT INTO updates (user_update) VALUES ('$user_update')";
$r = @mysqli_query ($dbc,$q);



// telling you if it has been uploaded or not 
if($r){
    echo "you have successfully inserted";
} else{
    echo "this did not work";
}


?>

1 个答案:

答案 0 :(得分:0)

从user_update中删除$,因为你想比较字段的值,而不是自身的值。

 $query = mysqli_query($con, "SELECT * FROM updates WHERE user_update ='".$items['id']."'");