Php 在Mysqli_查询中检查并返回值
我是Android开发人员,正在尝试使用PHP和Mysqli为注册用户制作一个API。我已经做了如下APIPhp 在Mysqli_查询中检查并返回值,php,android,mysql,mysqli,Php,Android,Mysql,Mysqli,我是Android开发人员,正在尝试使用PHP和Mysqli为注册用户制作一个API。我已经做了如下API <?php include("dbconnection.php"); $email= $_GET['email']; $query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'"); if (!$query){ die('Error: ' .
<?php
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
$response='success';
}else{
$sql = "INSERT INTO tbl_user(email)VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response='success';
}else {
$response='error';
}
}
echo json_encode($response);
?>
基本上,我将电子邮件作为参数传递,比如example.com/login=abc@gmail.com
我要检查电子邮件是否已经在数据库表中。如果数据库中存在电子邮件,我希望返回用户id作为响应,如果电子邮件不在数据库中,我希望将该电子邮件添加到数据库中,并希望返回用户id。我已使API按照我的要求正常工作,但我不知道如何返回与该电子邮件一起定位的用户id。让我知道是否有人能给我解决难题的想法。谢谢首先,您应该使用
PreparedStatement
来避免sql注入
然后,第二步可以使用下面的代码将创建一个包含消息和用户id的数组
include("dbconnection.php");
$email= $_GET['email'];
$query = mysqli_query($conn, "SELECT * FROM tbl_user WHERE email='".$email."'");
if (!$query){
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
// assign message to response array
$response['message']='success';
// Get the results data
while($row = mysqli_fetch_assoc($query)) {
// assign user_id to response array
$response['user_id'] = $row['user_id'];
}
}else{
$sql = "INSERT INTO tbl_user(email) VALUES ('".$email."')";
if (mysqli_query($conn, $sql)) {
$response['message']='success';
// assign last inserted id to response array
$response['user_id'] = mysqli_insert_id($conn);
}else {
$response['message']='error';
}
}
echo json_encode($response);
准备好的语句可以帮助您保护SQL语句免受SQL注入攻击。什么是
用户id
?是自动增值吗?@Ravi是的……它的主键叫user_idHi!谢谢…添加新记录效果很好。但是,如果电子邮件存在,它的给我错误称为警告:mysqli_fetch_assoc()期望参数1是mysqli_result,在“while($row=mysqli_fetch_assoc($result)){”中为空。感谢这些查询是不安全的。这个答案开始提供了很好的建议,但并没有真正慷慨地贯彻到底。遗憾的是我不能使用它。