gpt4 book ai didi

php - 检查数据是否已经存在于MySQL中

转载 作者:可可西里 更新时间:2023-11-01 07:56:00 25 4
gpt4 key购买 nike

我正在尝试检查数据条件。如果数据已经存在,则不会插入。否则会插入。但问题是数据仍然会被插入,尽管它已经存在了!

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

最佳答案

您的代码中存在多个问题。我将从回答你的问题开始。 $check 将永远不会被设置,因为您的查询没有被执行。 $sql 中缺少 $。此外,您总是需要在查询中使用用户输入之前对其进行清理/转义。如果您不对其进行清理,那么黑客可能会在您的查询中注入(inject)不需要的代码,从而执行您不想执行的操作。请参阅下面更新和优化的代码:

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

关于php - 检查数据是否已经存在于MySQL中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35472844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com