[英]Check whether the data already exists in MySQL
I'm trying to do a checking data condition. 我正在尝试检查数据状况。 If data already exists, it will not inserted.
如果数据已存在,则不会插入。 Otherwise it will inserted.
否则会插入。 But the problem is data still get inserted although it already exists !
但问题是数据仍然插入虽然它已经存在!
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$project = strtoupper($_POST['project']);
if($project != null)
{
//Importing our db connection script
require_once('dbConnect.php');
$sql="SELECT * FROM Project WHERE project='$project'";
$check=mysqli_fetch_array(mysqli_query($con,sql));
if(isset($check))
{
// no need insert
}
else{
//Creating an sql query
$sql = "INSERT INTO Project(project) VALUES ('$project')";
}
//Executing query to database
if(mysqli_query($con,$sql)){
echo ' Added Successfully';
}else{
echo 'Could Not Add Project';
}
}
else
{
echo "data is null";
}
//Closing the database
mysqli_close($con);
}
?>
There were multiple issues in your code. 您的代码中存在多个问题。 I'll start with answering your question.
我将首先回答你的问题。
$check
will never be set because your query isn't being executed. 永远不会设置
$check
因为您的查询没有被执行。 The $
is missing from $sql
. 在
$
从缺少$sql
。 Additionally, you always need to sanitize/escape user input before using it in a query. 此外,在查询中使用之前,您始终需要清理/转义用户输入。 If you do not sanitize it, then it is possible that a hacker might inject unwanted code into your query, doing things that you didn't want to be done.
如果你没有对它进行消毒,那么黑客可能会在你的查询中注入不需要的代码,做你不想做的事情。 See the updated and optimized code below:
请参阅下面的更新和优化代码:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
if(isset($_POST['project']) && !empty($_POST['project'])){
//Importing our db connection script
require_once('dbConnect.php');
$project = strtoupper($_POST['project']);
//Security: input must be sanitized to prevent sql injection
$sanitized_project = mysqli_real_escape_string($con, $project);
$sql = 'SELECT * FROM Project WHERE project=' . $sanitized_project . ' LIMIT 1';// LIMIT 1 prevents sql from grabbing unneeded records
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
// a match was found
// no need insert
}
else{
//Creating an sql query
$sql = "INSERT INTO Project(project) VALUES ('$sanitized_project')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo('Added Successfully');
}
else{
echo('Could Not Add Project');
}
}
else{
echo('data is null');
}
//Closing the database
mysqli_close($con);
}
?>
Correct this line $check=mysqli_fetch_array(mysqli_query($con,sql));
纠正这一行
$check=mysqli_fetch_array(mysqli_query($con,sql));
, you missed $
before sql
. ,你在
sql
之前错过了$
。 That's why condition is evaluating to false. 这就是条件评估为假的原因。
执行sql应该放入“需要插入”其他{}。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.