Reputation: 1
im trying to check duplicates before I insert a statement, and after looking at some posts i still couldn't get what went wrong in my php, below is my code and please let me know if i either have something in my php or in my sql.. thanks!!
date_default_timezone_set("America/Los_Angeles");
$time = date("y-m-d H:i:s");
//$name = $_POST["name"];
$name = "bulbasaur";
$lcname = strtolower($name);
if(empty($_POST["nickname"])) {
$nickname = strtoupper($name);
} else {
$nickname = $_POST["nickname"];
}
//Connect SQL & PHP
$host = getenv('IP');
$user = getenv('C9_USER');
$password = "";
$dbname = "hw7";
// Create connection
$ds = "mysql:host={$host};dbname={$dbname};charset=utf8";
// Make connection
try {
$db = new PDO($ds, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
header("Content-Type: text/plain");
echo "Can not connect to the database. Please try again later. \n";
echo "Error details: $ex \n";
die();
}
//check duplicates
$subsql = "SELECT name FROM Pokedex WHERE name = {$name})";
try {
$dupe = $db->prepare($subsql);
$param = array("name" => $name);
$dupe->execute($param);
}
catch(PDOException $ex) {
die($ex->getMessage()."\n");
}
if($dupe-> rowCount() > 0) {
echo "fail";
} else {
$sql = "INSERT INTO Pokedex(name, nickname, datefound)
VALUES (:name, :nickname, :datefound);";
try{
$stmt = $db->prepare($sql);
$params = array(":name" => $lcname,
":nickname" => $nickname,
":datefound" => $time);
$stmt->execute($params);
}
catch(PDOException $ex) {
die($ex->getMessage());
}
}
i received this error message- please help me ...
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
Since the message mention something about my sql, here is my code for my sql-
DROP TABLE IF EXISTS Pokedex;
CREATE TABLE Pokedex(
name VARCHAR(30) PRIMARY KEY,
nickname VARCHAR(30),
datefound DATETIME
);
INSERT INTO Pokedex(name,nickname,datefound) VALUES
("Pikachu","Pika","2018-01-03 12:23:44");
Upvotes: 0
Views: 484
Reputation: 782285
You have two problems.
First, you have a typo, an extra )
at the end of the query. That's what's causing the syntax error.
Second, you're using a prepared statement with $param = array("name" => $name);
. So you don't need to put {$name}
, in the query, you have to put a placeholder.
$subsql = "SELECT name FROM Pokedex WHERE name = :name";
Alternatively, instead of checking for the duplicate yourself, you could just attempt the INSERT
. If it has a duplicate name, you'll get an error, and you can check for this in the catch
block.
catch(PDOException $e) {
if ($e->code == 2627) { // Violation of primary key constraint
echo "fail";
} else {
die($ex->getMessage());
}
}
Upvotes: 0