$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO cinema (name, genre, year, oscar, watched) VALUES(?,?,?,?,?)";
$q = $pdo->prepare($sql);
$q->execute(array($name, $genre, $year, $oscar, $seen));
Database::disconnect();
Asked
Active
Viewed 479 times
-1
-
3And your question is? – kero Mar 15 '15 at 16:19
-
1@kingkero Maybe it's an easter egg, you have to find it :D – Rizier123 Mar 15 '15 at 16:20
-
1@Rizier123 Which is coming up soon, *woohoo!* Hop hop – Funk Forty Niner Mar 15 '15 at 16:21
-
*"check mysql db before inserting values using pdo in php"* - Query before to see if it exists. Oh, and *check FOR what?*. – Funk Forty Niner Mar 15 '15 at 16:22
-
2@Rizier123 Mhm .. I am quite certain the table is badly configured (eg missing `UNQIUE` constraints), but the question is, what should happen after the table is queried before the `INSERT`. Either give an error (so the first query is useless anyway) or do an `UPDATE` (which has been asked&answered a ton of times as well) – kero Mar 15 '15 at 16:23
-
hhhh ok sorry my question is that I want to check db table if the name and year exist if exist echo"already in db" else the code jump to insertion part that's my question – joe_black Mar 15 '15 at 16:23
-
Well, you can't use `rowCount()` on SELECT, so that's out. You'll need to use `count()`. Why the @#$& did they not let PDO use `rowCount()` for stuff like that, I'll never know. *Giving my head a shake.* – Funk Forty Niner Mar 15 '15 at 16:24
-
Apparently, in some cases you can. `if ( $sthandler->rowCount() > 0 )` check http://stackoverflow.com/q/8315835/ - http://stackoverflow.com/q/23305300/ try that and see. But the manual http://php.net/manual/en/pdostatement.rowcount.php states *PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement.* – Funk Forty Niner Mar 15 '15 at 16:29
-
You have an answer given below. However, as @kingkero said, using a unique constraint is your best bet. You just need to code accordingly with the error handling. – Funk Forty Niner Mar 15 '15 at 16:42
-
$query = "SELECT COUNT(*) AS c FROM cinema WHERE name = ? AND year = ?"; $qq = $pdo->prepare($query); i did this so what can i do after those lines – joe_black Mar 15 '15 at 21:48
1 Answers
0
Just do another query before you do the INSERT:
SELECT COUNT(*) as c FROM cinema WHERE name = ? and year = ?
Do the usual prepare/bind/fetch stuff and if ($row['c'] > 0)
then you output your error message - otherwise you continue to your INSERT
.

Peter Bowers
- 3,063
- 1
- 10
- 18