我有一个问题,当我执行我的功能时,表中没有数据存储。我的数据库连接正常工作,因此与数据库本身通信时没有错误。这是我的代码:
PHP:
//function for creating a bet
function CreateBet() {
//make variables global instead of local
global $con;
global $CharTick;
global $hash;
global $created_by;
//infinite loop, no <= or >=
for($cycle=0; ; $cycle++) {
//define result - select coinflip table, gameid column and for what number to look
$result = $con->query("SELECT * FROM coinflip WHERE gameid = $cycle");
//check if table 'coinflip' in 'gameid' contains an already existing number, looking
if($result->num_rows == 0) {
//if that number is not used, create it
$sql = "INSERT INTO coinflip (gameid, hash_sha1, hash_original, created_by) VALUES ($cycle, $hash, $CharTick, $created_by)";
$con->query($sql);
//stop the for loop
break;
}
}
}
//execute the function for creating a bet
CreateBet();
用于创建与数据库的连接的PHP代码:
//connect to mariadb
$con = @mysqli_connect('localhost', 'root', '', 'testing');
//check if connection is NOT alright
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
//echo if the connection was alright
echo 'Connected to MariaDB';
SQL:
CREATE TABLE `coinflip` (
`gameid` varchar(128) NOT NULL,
`winner` varchar(128) NOT NULL,
`ticket` varchar(128) NOT NULL,
`hash_sha1` varchar(128) NOT NULL,
`hash_original` varchar(128) NOT NULL,
`created_by` varchar(128) NOT NULL,
`joined_by` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `coinflip` (`gameid`, `winner`, `ticket`, `hash_sha1`, `hash_original`, `created_by`, `joined_by`) VALUES
('0', '', '', '', '', '', ''),
COMMIT;
谢谢:)
答案 0 :(得分:1)
您缺少“引用”您的字符串值:
$con->query($sql);
您应该测试if (!$con->query($sql)) {
echo "Error: " . $con->error;
}
的结果以查看错误:
gameid
同样gameid
似乎是一个整数,因此您可以对$con->query("SELECT * FROM coinflip WHERE gameid = '$cycle'");
列使用整数类型,或者也可以在以下位置使用引号:
$result->num_rows > 0
最后,您可以使用parameterized queries来避免此类问题和可能的SQL注入。