I am attempting to insert some data via prepared statements in PHP. I have the following code which is not inserting for me. I also have the following code set already
ini_set('display_errors', 1);
error_reporting(~0);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$sqlInsert = "INSERT INTO deck_cards (deckid, cardid, qty) VALUES (?,?,?)";
$stmtInsert = $conn->prepare($sqlInsert);
if ($stmtInsert)
{
$stmtInsert->bind_param("sss", $deckid, $cardid, $cardcount) or trigger_error($stmtInsert->error, E_USER_ERROR);
$stmtInsert->execute() or trigger_error($stmtInsert->error, E_USER_ERROR);
echo "Check if this ran";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
$conn->close();
}
$stmtInsert->close();
}
catch (Exception $ex)
{
echo 'Exception occurred '.$ex->getTraceAsString();
}
When this executes, I do see the text "Check if this ran" but no other messages. The data is not inserted into the database. Additionally, I echo'd the sql string and variables and ran it against the MySQL directly and it inserted ok. Not sure what is happening in my very straightforward code above.
Additionally, inserts are happening ok in other pages within my app, but this page for some reason isn't working.
I know it's overkill on my error reporting, but I threw everything I could think of to see if there is an error somewhere, but this one is a head scratcher for me. Thanks for any assistance!
Related
RollBack () and beginTransaction() not work in my PHP PDO and my table type is innoDB. In the following code my $sql1 is correct and my $sql2 is wrong (I added d to $last_id to just make it wrong). But it still executes sql1 meaning roll back no effect. Thank you for your advice.
<?php
include 'connect.php';
// Get multiple input field's value
try {
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Starts our transaction
$conn->beginTransaction();
foreach ($_POST['phone'] as $value) {
$sql1 = "INSERT INTO tbl_contact_info (type)
VALUES ('$value')";
// use exec() because no results are returned
$conn->exec($sql1);
$last_id = $conn->lastInsertId();
$sql2="INSERT INTO tbl_img (img_type)
VALUES ('$dlast_id')";
$conn->exec($sql2);
}
// Commits out queries
$conn->commit();
echo "New record created successfully";
}
catch(PDOException $e)
{
// Something borked, undo the queries!!
$conn->rollBack();
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
First of all (and sorry it it's obvious but I realised it's not always clear to everyone) SQL and PHP are different languages. MySQL Server will not react to Undefined variable notices triggered in PHP code.
Secondly, notices are not exceptions so they cannot be caught with try/catch statements. (You can certainly write a custom error handler that will throw exceptions on errors but it doesn't seem to be the case here.)
I run the following code to add a new user to a table of data base, but this code doesn't work correctly.
<?php include ("database/configdb.php");//configuration file of pdo to database connection
if(isset($_GET['uname'])&&isset($_GET['pass'])&&isset($_GET['email'])&&isset($_GET['fname'])&&isset($_GET['lname'])){
//check username
$sql="SELECT COUNT(*) FROM users WHERE uname=:username";
$rslt=$connect->prepare($sql);
$rslt->execute(array(":username"=>$_GET['uname']));
$num=$rslt->fetchColumn();
if ($num==1) { echo "exist"; exit();}
else{
//end check username
$sql = "INSERT INTO users (fname,lname,uname,password,email,avatar,bdate,rdate,degree,popularity,sex,lock,lang,country,phone) VALUES(:fname1,:lname1,:uname1,:pass1,:email1,'','','','','','','','','','')";
$result=$connect->prepare($sql);
$query=$result->execute(array(
":fname1"=>$_GET['fname'],
":lname1"=>$_GET['lname'],
":uname1"=>$_GET['uname'],
":pass1"=>$_GET['pass'],
":email1"=>$_GET['email']
));
if ($query){
echo "ok"; exit();
}
else{
echo "error"; exit();
}
}
}
else
{
echo "invalid";
}
?>
when i run this code, the result that printed is "error".
how can resolve that? thanks...
You're using a MySQL reserved word which is lock
Either wrap it in ticks, or rename it to something else.
INSERT INTO users ... sex,`lock`,...
Even though you have '' assigned as the value to be used for it, the column name "lock" still needs to be wrapped in ticks.
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Checking for errors would have signaled the error, placed under your connection:
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)
I.e.:
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
right after the connection is opened.
Consult: http://php.net/manual/en/pdo.errorinfo.php and get the real error.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Building a small project and trying to learn as I go along.
I get error codes fine if tables are misnamed etc but if I try to UPDATE an empty row I do not get an error. I want to but it isn't telling me I have screwed up. Is this normal?
public function updateMessage($id){ //done
try{
global $pdo;
$temp=$this->_message;
$sql = "UPDATE message SET content=:val WHERE id=$id";
$s = $pdo->prepare($sql);
$s->bindValue(':val',$temp);
$s->execute();
}
catch (PDOException $e)
{ $loc = $_SERVER['PHP_SELF'];
$output = "Unable to connect to the database server: $loc <br><h3>Please contact
Steve via text on ###### quoting:</h3><h5>" . $e->getMessage() . "<br>
Found at $loc.</h5>
<h3>Thanks. </h3>". "<br>"."<br>" ;
include $_SERVER['DOCUMENT_ROOT'] ."/beta01/includes/output.html.php";
exit();
}
}
As I said it works as expected with most errors just not on the empty update problem.
$sql = "UPDATE message SET content=:val WHERE id=$id";
If it's an "empty row" (assuming I understand you right), then it doesn't meet the condition WHERE id=$id, so it worked - it updated the contents of message for every row with that id (there were none).
It sounds like you want to know if no rows were affected by the query, in which case you could do:
$s->execute();
if ($s->rowCount() < 1) {
//throw an exception, show a warning, whatever you want to do
}
I have writen this pice of code that should insert into my Database some event data, but it does not insert a thing in the DB, can you tell me why?
try {
$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $excepiton ) {
echo "Connection error :" . $excepiton->getMessage();
}
try{
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name) VALUES (:event_id, :event_end_time, :event_location, :event_name) ON DUPLICATE KEY UPDATE event_id = :event_id, event_end_time = :event_end_time, event_location = :event_location, event_name = :event_name";
$stm = $db->prepare($sql);
$stm->execute(array(":event_id" => $event[id], ":event_end_time" => $event[end_time], ":event_location" => $event[location], ":event_name" => $event[name]));
}
catch ( PDOException $exception )
{
// decomentati sa vedeti erorile
echo "PDO error :" . $exception->getMessage();
}
Thanks
The code you've posted is different than the code you're running as the posted code would result in a syntax error at parse time and never actually run.
However, what's happening is the SQL being sent to the prepare method is not valid in some way so that the result returned and stored in $stm is a boolean (false) rather than a valid statement object. Double check your SQL (you could try running it in another application such as phpMyAdmin or via the mysql command-line program) to ensure its validity. You could also add some error handling to find the cause with:
$stm = $db->prepare($sql);
if (!$stm) {
die($db->errorInfo());
}
Edit: You've modified the posted source code which now shows use of exception handling. However, you've commented out the line that echos the exception message. This information will be useful in telling you what's causing the error condition. Uncomment to see the message (which will most likely inform you that the SQL is invalid and which part of it caused the error).
Try to remove the <br> tag from the first line and a " is messing
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name);"
Well basically I have this script that takes a long time to execute and occasionally times out and leaves semi-complete data floating around my database. (Yes I know in a perfect world I would fix THAT instead of implementing commits and rollbacks but I am forced to not do that)
Here is my basic code (dumbed down for simplicity):
$database = new PDO("mysql:host=host;dbname=mysql_db","username","password");
while (notDone())
{
$add_row = $database->prepare("INSERT INTO table (columns) VALUES (?)");
$add_row->execute(array('values'));
//PROCESSING STUFF THAT TAKES A LONG TIME GOES HERE
}
$database = null;
So my problem is that if that if the entire process within that while loop isn't complete then I don't want the row inserted to remain there. I think that somehow I could use commits/rollbacks at the beginning and end of the while loop to do this but don't know how.
Take a look at this tutorial on transactions with PDO.
Basically wrap the long running code in:
$dbh->beginTransaction();
...
$dbh->commit();
And according to this PDO document page:
"When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back. "
So you will lose the transaction that was pending when the script timed out.
But really, you ought to redesign this so that it doesn't depend on the scriipt staying alive.
You need to use InnoDB based tables for transactions then use any library like PDO or MySQLi that supports them.
try
{
$mysqli->autocommit(FALSE);
$mysqli->query("insert into tblbook (id,cid,book) values('','3','book3.1')");
echo $q_ins=$mysqli->affected_rows."<br>";
$mysqli->query("update tblbook set book='book3' where cid='3'");
echo $q_upd=$mysqli->affected_rows."<br>";
$mysqli->commit();
}
catch(PDOException $e)
{
$mysqli->rollback();
echo $sql . '<br />' . $e->getMessage();
}
<?php
//This may help someone....This code commit the transactions
//only if both queries insert and update successfully runs
$mysqli=new mysqli("localhost","user_name","password","db_name");
if(mysqli_connect_errno())
{
echo "Connection failed: ".mysqli_connect_error();
}
else
{
$mysqli->autocommit(FALSE);
$mysqli->query("insert into tblbook (id,cid,book) values('','3','book3.1')");
echo $q_ins=$mysqli->affected_rows."<br>";
$mysqli->query("update tblbook set book='book3' where cid='3'");
echo $q_upd=$mysqli->affected_rows."<br>";
if($q_ins==1 && $q_upd==1)
{
$mysqli->commit();
echo "Commit<br>";
}
else
{
$mysqli->rollback();
echo "Rollback<br>";
}
}
?>