php - How can I make sure my query inserts a new row? -
this question has answer here:
- pdo mysql: how know if insert successful 7 answers
here query:
$db->query("insert mytable(col1, col2) values('val1', 'val2')");
i'm trying understand query inserts new row or not? how can determine it?
note: i'm not using execute()
in case.
taken directly w3schools.com/php/php_mysql_insert...
$sql = "insert myguests (firstname, lastname, email) values ('john', 'doe', 'john@example.com')"; if ($conn->query($sql) === true) { echo "new record created successfully"; } else { echo "error: " . $sql . "<br>" . $conn->error; }
you're looking this: if ($conn->query($sql) === true)
edit: sorry, took wrong example @drew pointed out!
below correct snippet, make use of execute, think should (correct me if i'm wrong!)
this link might of more use: pdostatement.execute
try { $conn = new pdo("mysql:host=$servername;dbname=$dbname", $username, $password); // set pdo error mode exception $conn->setattribute(pdo::attr_errmode, pdo::errmode_exception); $sql = "insert myguests (firstname, lastname, email) values ('john', 'doe', 'john@example.com')"; // use exec() because no results returned $conn->exec($sql); echo "new record created successfully"; } catch(pdoexception $e) { echo $sql . "<br>" . $e->getmessage(); }
and
<?php function customexecute(pdostatement &$sth, array $params = array()) { if (empty($params)) return $sth->execute(); return $sth->execute($params); } ?>
hope helps!
Comments
Post a Comment