测试记录是否存在并选择sql查询

时间:2018-06-12 06:51:04

标签: php sql ajax pdo mariadb

为什么我的代码不起作用?

<?php
session_start();
require_once("connecting-to-database.php");

$query = $pdo->prepare("SELECT * FROM `timetables` WHERE `who` = :who");
$query->execute(array(
":who" => $_SESSION["id"]["username"]));

if ($query->rowCount() > 0) {
    $query = $pdo->prepare("UPDATE `timetables` SET `who` = :who, `day` = :day");
    $result = $query->execute(array(
    ":who" => $_SESSION["id"]["username"],
    ":day" => $_GET["timetable"]));
} else {
    $query = $pdo->prepare("INSERT into `timetables`(`who`, `day`) VALUES(:who, :day)");
    $result = $query->execute(array(
    ":who" => $_SESSION["id"]["username"],
    ":day" => $_GET["timetable"]));
}

我看不到错误,因为我正在使用方法GET的AJAX。

在主网站上我有:

var rocket = JSON.stringify(timetable);

var xhttp = new XMLHttpRequest();
xhttp.open("GET", encodeURI("modify-timetable.php?timetable=" + rocket), true);
console.log(rocket);

如果你的信息较少,我可以再给你一些。

1 个答案:

答案 0 :(得分:0)

了解如何使用IODKU。它可以替换您提供的所有代码。

INSERT into `timetables`    (`who`, `day`)
    VALUES                  (:who,  :day)
    ON DUPLICATE KEY UPDATE `day` = :day

(确实需要whoPRIMARYUNIQUE密钥。)