gpt4 book ai didi

php - MySQL 查询失败?

转载 作者:行者123 更新时间:2023-11-29 11:23:55 25 4
gpt4 key购买 nike

我的 MySQL 查询不断失败,我不明白为什么,我仔细阅读了它,显然我错过了表名等周围的反引号 (`),所以我添加了它们,但没有任何更改。这是代码:

$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);

try{
$check = $db->prepare("SELECT `userID` from `userData` WHERE `userID` = :accountID");
$check->bindParam(':accountID', $accid, PDO::PARAM_INT);
$check->execute();
if(!$check->execute()){
die(var_dump($db->errorInfo()));
}else{
if($check->rowCount() > 0) {
$creditsQuery = $db->prepare("SELECT `userCredits` FROM `userData` WHERE `userID` = :accountID3");
$creditsQuery->bindParam(":accountID3", $accid, PDO::PARAM_INT);
$creditsQuery->execute();
//Set Credits To Variable From Database Column
$credits = $creditsQuery->fetch(PDO::FETCH_ASSOC);
}else{
$sql = $db->prepare("INSERT INTO `userData` (`userID`, `userCredits`) VALUES (:accountID2, '0')");
$sql->bindParam(':accountID2', $accid, PDO::PARAM_INT);
$sql->execute();
if(!$sql){
die('Server Error: 404Insert, Please Contact A Member Of Staff If This Error Continues.');
}
}
}
}catch(PDOException $e){
die ("Server Error: 404Connection, Please Contact A Member Of Staff If This Error Continues.");
}

errorInfo 行显示: array(3) { [0]=> string(5) "00000"[1]=> NULL [2]=> NULL }

因此,数据库成功连接,因为 try block 没有抛出异常。所以我真的不知道。

谢谢

马特

最佳答案

您的代码中有几个错误

  • PDO 未处于异常模式
  • $accid 不包含值
  • 您使用的是 bindParam 而不是 bindValue - 它们之间存在差异,而且非常重要
  • 你不必用反引号括起任何内容,除非它是 MySQL 保留字
  • 您正在检查 PHP 中记录是否存在 - 这是 MySQL 的工作。 PHP 无法准确判断 MySQL 中是否存在记录。 PHP 和 MySQL 连接之间存在微小的延迟(在人类测量中是微小的,在计算机测量中是亿万年)。当结果到达并被 PHP 解析时,另一个进程可能已经插入了该记录。这就是为什么我们让 MySQL 负责唯一性和数据完整性。

请阅读我发布的代码的注释并根据您的需要进行调整:

<?php

/**
* Create PDO object and set it into exception mode
*/

try {
$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}


try {
// Replace with actual value
$user_id = 1;

// Pay close attention to IGNORE keyword - it's extremely important
// and it requires a unique index to be placed on userID column
// I assumed that userID is primary key
$query = "INSERT IGNORE INTO userData (userID, userCredits) VALUES (:userID, 0)";

$stmt = $db->prepare($query);

$stmt->bindValue(':userID', $user_id);

$stmt->execute();

} catch(PDOException $e) {
echo 'An error occurred: '. $e->getMessage();
}

关于php - MySQL 查询失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38528775/

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