美好的一天, 我是 PHP/MySQL 的新手,我尝试从 ajax 发送请求并在具有多个参数的数据库中选择一行。 这是做到这一点的好方法吗?
AJAX (Jquery):
function readLine(name, firstname) {
$.ajax({
type: "post",
url: "./php/readLine.php",
dataType: 'json',
data: { name: name, firstname: firstname },
success: function(data) {
console.log(data);
}
error: function(data) {
console.log("An error occured!");
}
});
}
PHP:
<?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
$to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>
感谢您的帮助。
最佳答案
您可以将 PDO 与准备好的语句一起使用,这将确保用户输入是安全的。像这样:
try {
$db = new PDO('mysql:dbname=db_name;host=localhost', 'db_user', 'db_password');
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
$sql = "SELECT * FROM table1 WHERE firstname=:firstname AND name=:name";
$stmt = $db->prepare($sql);
$stmt->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STRING);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STRING);
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
将前 5 行移动到包含中,然后您只需要此代码一次。
关于javascript - 选择具有多个参数的行(ajax 和 PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44946521/