The Following code will display "12" on the screen. That is all. These echo numbers were added for debugging.
It should Display "123" and insert into a MySQL database the variables in the statement.
For some reason it just ends at the prepare statement. The fail() error check never getting called. Actually, nothing gets called after the prepare statement.
I have been all over the site and believe I am doing everything required properly, but it is more then likely something I did.
Can anyone tell me why the prepare statement is failing this way?
$query = "insert into member(mail, user, val) values (?, ?, ?)";
$uuu = blah#blah.com;
$hhh = Blah Williams;
$val = 0;
echo "1";
if($stmt = $this->conn)
{
echo "2";
$stmt->prepare($query) || $this->fail('MySQL prepare', $stmt->error);
echo "3";
$stmt->bind_param('ssi', $uuu, $hhh, $val)
|| $this->fail('MySQL bind_param', $stmt->error);
$stmt->execute();
if (!$stmt->execute())
{
if ($stmt->errno === 1062 /* ER_DUP_ENTRY */)
{
$this->fail('This username is already taken');
}
else
{
$this->fail('MySQL execute', $stmt->error);
}
}
}
else
{/*error check*/
$this->fail('MySQL insert prepare failed', $stmt->error);
return 0;
}
$stmt->close();
return true;
You should use as your assignment will always be true.
$stmt = $this->conn->prepare($query);
To check why it's failing, use:
var_dump($stmt->errorInfo());
Related
I have the following code which i'm trying to obtain a single row of data into an array. I'm unsure if i'm mixing prepared statements and PDO.
I'm getting the following error:
Uncaught Error: Cannot use object of type mysqli_stmt as array in...
The Code:
// Prepare a select statement
$sql = "SELECT * FROM pupils WHERE pupil_id = ?";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("i", $param_pupil_id);
// Set parameters
$param_pupil_id = $_POST['pupil_num'];
// Attempt to execute the prepared statement
if($stmt->execute()){
$stmt->store_result();
if($stmt->num_rows == 1){
$stmt->bind_result($id, $pupil_id, $name, $eal, $pp);
//Updated code
echo $stmt->fetch()->$name;
} else{
echo "error";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
I need to know how to get the result of a select statement that is executed after an insert statement as one execute in PDO.
My PDO connection parameters are as follows:
$opt = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => true];
$conn = new PDO($dsn, $user, $pass, $opt);
I have the following helper function that i use for my PDO statement Execution:
function databaseExecute($SQL, $BIND_P, &$BIND_R) {
global $conn;
$stmt = $conn->prepare($SQL);
if ($stmt->execute($BIND_P)) {
if ($BIND_R !== false) {
//Type testing is important here
$tmp = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (!$tmp || count($tmp) == 0) {
return false;
}
$BIND_R = $tmp;
} else {
$stmt->closeCursor();
}
return true;
}
$stmt->closeCursor();
return false;
}
My function itself is:
/**
* Adds the current purchase object to the database table
* #return true if success
*/
public function pushToDB() {
global $tbl_purchases;
//We don't push purchaseID since that field is auto handled by the database
$sql = "INSERT INTO " . $tbl_purchases . " (ProductID, UID, TID, GenDate, KeyIDs, Total, Assigned) VALUES (?, ?, ?, ?, ?, ?, ?); SELECT LAST_INSERT_ID();";
$result = array();
if (databaseExecute($sql, array(
$this->getProductID(),
$this->getUID(),
$this->getTID(),
$this->getGenDate(),
$this->getKeyIDsJSON(),
$this->getTotal(),
$this->getAssigned(),
), $r)) {
var_dump($result);
$this->_setPurchaseID($result[0]);
return true;
}
trigger_error("Purchase::pushToDB - Could not push purchase to database", E_USER_ERROR);
return false;
}
But this throws a general error
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error when i attempt to fetchAll
In this situation, how do i get the result of the SQL execution?
PS: Using Two executes is not acceptable here.
Using Two executes is not acceptable here.
This is but a delusion.
Use either second query or - better - a dedicated function PDO::LastInsertId(). But with your rather poorly designed function it could be a problem. So be it 2 queries.
So change your functions to
function databaseExecute($SQL, $BIND_P = array();) {
global $conn;
if (!$BIND_P)
{
return $conn->query($SQL);
}
$stmt = $conn->prepare($SQL);
$stmt->execute($BIND_P);
return $stmt;
}
and
public function pushToDB() {
global $tbl_purchases;
//We don't push purchaseID since that field is auto handled by the database
$sql = "INSERT INTO $tbl_purchases
(ProductID, UID, TID, GenDate, KeyIDs, Total, Assigned)
VALUES (?, ?, ?, ?, ?, ?, ?)";
databaseExecute($sql, array(
$this->getProductID(),
$this->getUID(),
$this->getTID(),
$this->getGenDate(),
$this->getKeyIDsJSON(),
$this->getTotal(),
$this->getAssigned(),
));
$id = databaseExecute("SELECT LAST_INSERT_ID()")->fetchColumn();
$this->_setPurchaseID($db);
return true;
}
}
You can alter your databaseExectute function to take an extra parameter of 'SecondResult' (for example), then change it to something like...
function databaseExecute($SQL, $BIND_P, &$BIND_R,$SecondResult) {
global $conn;
$stmt = $conn->prepare($SQL);
if ($stmt->execute($BIND_P)) {
if ($BIND_R !== false) {
//Type testing is important here
if ($SecondResult) $stmt->nextRowSet(); // this will ensure that the fetchAll will return the data from the 2nd query
$tmp = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
if (!$tmp || count($tmp) == 0) {
return false;
}
$BIND_R = $tmp;
} else {
$stmt->closeCursor();
}
return true;
}
$stmt->closeCursor();
return false;
}
I just typed this in to here directly, I haven't tested it, but it should work.
Also, I'm not saying that the other comments are wrong, and there might be a better way of doing this, but you CAN run two queries within the same 'statement'.
I am having some trouble with prepared statements. Basically, this query is returning no rows, even though I know for a fact that this query should return multiple rows. I thought this was just a problem due to SQL injections, but maybe I'm doing something else wrong here, I don't know. If I take out the check for how many rows there are, I get an error:
PHP Fatal error: Call to a member function fetch_array()
Any help would be appreciated!
$stmt = $mysqli->prepare("SELECT sid from SDS WHERE uid=? AND dst=?");
$stmt->bind_param('ss',$username,$structureType);
$stmt->execute();
$stmt->bind_result($results);
$stmt->fetch();
if ($results) {
if($results->num_rows == 0) {
print("No results here.");
return 0;
}
$recordnames = array();
while ($next_row = $results->fetch_array()) {
$recordnames[] = $next_row['sid'];
}
return $recordnames;
}
When you use $stmt->bind_result($result); you are binding the sid from the database to the variable $results. So you cannot perform operations like :
if($results->num_rows == 0) { //... }
or
$results->fetch_array();
This is how I would do it :
<?php
$stmt = $mysqli->prepare("SELECT sid from SDS WHERE uid=? AND dst=?");
$stmt->bind_param('ss', $username, $structureType);
$stmt->execute();
$stmt->bind_result($sid);
$stmt->store_result();
if ($stmt->num_rows == 0)
{
print("No results here.");
$stmt->close();
return 0;
}
else
{
$recordnames = array();
while($stmt->fetch())
{
$recordnames[] = $sid;
}
return $recordnames;
}
?>
This way uses a different logic, check if the row count is 0, if so display "No results here", if not put results into the array.
I am receiving two errors in mysqli:
Warning: mysqli_stmt::execute(): (HY000/2014): Commands out of sync;
you can't run this command now in /.../ on line 235 240:
Commands out of sync; you can't run this command now Fatal error:
Cannot break/continue 2 levels in /.../ on line 241
I want to know that is the errors appearing because of the order of my queries and inserts below:
<?php
//connect to db
var_dump($_POST);
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";
if (!$optionstmt = $mysqli->prepare($optionquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$replyquery = "SELECT ReplyId FROM Reply WHERE (ReplyType = ?)";
if (!$replystmt = $mysqli->prepare($replyquery)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
// Prepare your statements ahead of time
$questionsql = "INSERT INTO Question (SessionId, QuestionId, QuestionContent, NoofAnswers, ReplyId, QuestionMarks, OptionId)
VALUES (?, ?, ?, ?, ?, ?, ?)";
if (!$insert = $mysqli->prepare($questionsql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
$answersql = "INSERT INTO Answer (SessionId, QuestionId, Answer)
VALUES (?, ?, ?)";
if (!$insertanswer = $mysqli->prepare($answersql)) {
// Handle errors with prepare operation here
echo __LINE__.': '.$mysqli->error;
}
//make sure both prepared statements succeeded before proceeding
if( $insert && $insertanswer)
{
$sessid = $_SESSION['id'] . ($_SESSION['initial_count'] > 1 ? $_SESSION['sessionCount'] : '');
$c = count($_POST['numQuestion']);
for($i = 0; $i < $c; $i++ )
{
$selected_option = "A-C";
$selected_reply = "Single";
// Bind parameter for statement
$optionstmt->bind_param("s", $selected_option);
// Execute the statement
$optionstmt->execute();
if ($optionstmt->errno)
{
// Handle query error here
echo __LINE__.': '.$optionstmt->error;
break 1;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$optionstmt->bind_result($optionid);
// This populates $optionid
$optionstmt->fetch();
// Bind parameter for statement
$replystmt->bind_param("s", $selected_reply);
// Execute the statement
$replystmt->execute();
if ($replystmt->errno)
{
// Handle query error here
echo __LINE__.': '.$replystmt->error;
break 2;
}
// This is what matters. With MySQLi you have to bind result fields to
// variables before calling fetch()
$replystmt->bind_result($replyid);
// This populates $optionid
$replystmt->fetch();
$results = $_POST['value'];
foreach($results as $id => $value)
{
$answer = $value;
$insert->bind_param("sisiiii", $sessid, $id, $_POST['questionText'][$i],
$_POST['numberAnswer'][$i], $replyid, $_POST['textWeight'][$i],
$optionid);
$insert->execute();
if ($insert->errno)
{
// Handle query error here
echo __LINE__.': '.$insert->error;
break 3;
}
$lastID = $insert->insert_id;
foreach($value as $answer)
{
$insertanswer->bind_param("sis", $sessid, $lastID, $answer);
$insertanswer->execute();
if ($insertanswer->errno) {
// Handle query error here
echo __LINE__.': '.$insertanswer->error;
break 4;
}
}
}
}
//close your statements at the end
$insertanswer->close();
$insert->close();
$replystmt->close();
$optionstmt->close();
}
?>
This is because you are closing the statement at proper time
Close the statement $insertanswer->close(); at the proper place or before another query
I am brand new to php and I ran into a problem that has already taken a few hours of poking around and researching and I could not find anything like it anywhere around the net.
Database:MyPHPAdmin winserver
Goal: Create a new row in table 'photo'. Take the last insert p_id for the current user and update the table accessible_to by creating a new row with that p_id.
I know I can create a trigger, and no it does not work either don't know why. Run out of ideas how.
What I found out by simply printing before-in-after the if statement
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)"))
is that it just bypasses it.
Please post your suggestions.
P.S. The if statement above to which I am referring has been twisted in several ways and yet it does not work.
The connection is already imported.
Thank you a lot.
if(!isset($_SESSION["id"])) {
echo "You are not logged in. ";
echo "You will be returned to the homepage in 3 seconds or click here.\n";
header("refresh: 3; index.php");
}
else {
//if the user have uploaded a photo, insert it into database
if(isset($_POST["ext"])) {
//insert into database, note that p_id is auto_increment
if ($stmt = $mysqli->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
$id = htmlspecialchars($_SESSION["id"]);
}
//The following function is fetching the last added p_id in PHOTO by the user with the current SESSION
//Do not simply get the last p_id in PHOTO because someone else might have just added another picture meanwhile
if ($stmt = $mysqli->prepare("select MAX(p_id) from photo where owner_id = ?")){
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($p_id);
if ($stmt->fetch()){
$p_id = htmlspecialchars($p_id);
}
}
echo "BEFORE accessible_to insertion";
echo '<br />';
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)")){
echo "Finally inside accessible_to insertion";
echo '<br />';
$stmt->bind_param("iss", $p_id, $id, 'T');
$stmt->execute();
$stmt->close();
}
echo "AFTER accessible_to insertion";
echo '<br />';
}
//if not then display the form for posting message
else {
echo "Something";
You can't boolean test an assignment and expect it to return a different result. What you want to test for is if $stmt->execute successfully executed or not.
$stmt = $mysql->prepare("insert into foo values (?,?)");
$stmt->bind_param(1,$f1);
$stmt->bind_param(2,$f2);
if ($stmt->execute()) {
... worked
} else {
... fubar
}
You have to start by calling mysqli::connect($server, $user, $pw, $db). The best way to do that is by constructing an object like:
$connection = new mysqli($server, $user, $password, $db);
if ($connection->errno)
{
echo "Connection failed";
echo $this->connection->error;
}
else
{
$stmt = $connection->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
}