I`m working with PDO and prepare statements and now I want to implement transactions, but when I do it I get this error:
Call to a member function beginTransaction() on a non-object in
The code is:
include_once '../../includes/db_connect.php';
include_once '../../includes/psl-config.php';
$mysqli->query("SET NAMES 'utf8'");
date_default_timezone_set('America/Mexico_City');
$hora = date("d-m-Y g:i a");
$mysqli->beginTransaction();
//OBTENCIÓN DE LA INFORMACIÓN
$id = $mysqli->real_escape_string( $_POST["id"] );
$fechaEntrada = date("Y-m-d");
$estatus = "Disponible";
$idUser = $mysqli->real_escape_string( $_POST['idUser'] );
$idUser = $idUser . " " . $hora;
//SELECIONAR INFORMACIÓN DE LA MAQUINA A ENTRAR
$sqlMaquina = "SELECT tipo, clave FROM maquinas_orden_renta WHERE id = $id";
$res = $mysqli->query($sqlMaquina);
$rows = $res->num_rows;
if (!$res)
printf("Error message: %s\n", $mysqli->error);
$objMaquinaRenta = $res->fetch_object();
$tipoMaquina = $objMaquinaRenta->tipo;
$idMaquina = $objMaquinaRenta->clave;
$sql = "UPDATE maquinas_orden_renta SET entradaReal = ?, estatus = ?,updated_by = ? WHERE id = ?";
$stmt = $mysqli->prepare($sql);
if ( false === $stmt )
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
$rc = $stmt->bind_param('sssi', $fechaEntrada, $estatus, $idUser, $id );
if ( false === $rc )
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
$rc = $stmt->execute();
if ( false === $rc )
die('execute() failed: ' . htmlspecialchars($stmt->error));
else{
if ($tipoMaquina == "conID") {
$sql2 = "UPDATE maquinas SET estatus = ?, updated_by = ? WHERE IdMaquina = ?";
$stmt = $mysqli->prepare($sql2);
if ( false === $stmt )
die('prepare2() failed: ' . htmlspecialchars($mysqli->error));
$rc2 = $stmt->bind_param('ss', $estatus, $idUser, $idMaquina );
if ( false === $rc2 )
die('bind_param2() failed: ' . htmlspecialchars($stmt->error));
$rc2 = $stmt->execute();
if ( false === $rc2 )
die('execute2() failed: ' . htmlspecialchars($stmt->error));
else
echo "Éxito";
}
}
if (false === $rc AND false === $rc2) {
echo "exito";
$mysqli->commit();
}else{
$mysqli->rollBack();
echo "error: $error";
}
$stmt->close();
So, I don`t know if the function beginTransaction is wrong or something.
It has to be $mysqli->begin_transaction(); on the connection not the statement. With a transaction you want to do more than one single statement.
http://php.net/manual/en/mysqli.begin-transaction.php
Related
I need to update if there is any field with the same model_name and only update the led_data and status
public function NewModelsBin($data)
{
$qry = "INSERT INTO LABELS_LEDS (PROJECT, MODEL_NAME, NO_LED,LED_PN,LED_DATA,STATUS) VALUES ('".$data['proyecto']."', '".$data['model_name']."', '".$data['no_led']."','
".$data['led_pn']."','".$data['led_data']."','".$data['status']."') ";
//"INSERT ON DUPLICATE KEY UPDATE LED_DATA (LED_DATA, STATUS) VALUES ('".$data['led_data']."', '".$data['status']."')";
echo $qry;
$stmt = sqlsrv_query( $this->conn,$qry);
if( $stmt === false) {
die( print_r( sqlsrv_errors() . " fallo la query " . $qry , true) );
}
sqlsrv_free_stmt( $stmt);
}
for this first, you will need to first run a select query to find in database entry with the model name after then add if condition. to add new entry id doesn't exist and update if exist.
public function NewModelsBin($data)
{
$qry="SELECT * FROM LABELS_LEDS WHERE MODEL_NAME='".$data['model_name']."'";
$stmt = sqlsrv_query( $this->conn,$qry);
if(sqlsrv_has_rows($stmt)){
//UPDATE QUERY HERE
}
else{
$qry = "INSERT INTO LABELS_LEDS (PROJECT, MODEL_NAME,
NO_LED,LED_PN,LED_DATA,STATUS) VALUES ('".$data['proyecto']."',
'".$data['model_name']."', '".$data['no_led']."','
".$data['led_pn']."','".$data['led_data']."','".$data['status']."') ";
echo $qry;
$stmt = sqlsrv_query( $this->conn,$qry);
if( $stmt === false) {
die( print_r( sqlsrv_errors() . " fallo la query " . $qry , true) );
}
sqlsrv_free_stmt( $stmt);
}
}
Here's my solution..
I'm having a problem finding specific records in my new program for the company. This is a ridiculously simple SQL query that I just can't get passed for the life of me.
Can anyone see a problem?
public function loadByKey($partNumber, $customerNumber, $rev){
$query = 'SELECT *'
.' FROM '.$this->myTableName
.' WHERE PartNumber = ?'
.' AND CustomerNumber = ?'
.' AND Rev = ?';
$conn = (new DBConnector)->connect();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$statement = $conn->prepare($query);
//var_dump($statement);
//var_dump($query);
//var_dump($conn);
$statement->bind_param('sis', $partNumber, $customerNumber, $rev);
$result = $statement->execute();
//var_dump($result);
//var_dump($statement);
//var_dump($customerNumber);
//var_dump($rev);
if ($statement->num_rows == 1) {
// output data of each row
$this->Properties = $statement->fetch_assoc();
var_dump($this->Properties);
$conn->close();
return true;
} else {
$this->Properties = [];
$conn->close();
return false;
}
}
Missing mysqli_stmt_store_result? – ficuscr
After delving into this and reading my older code this is the answer:
public function loadByKey($partNumber, $customerNumber, $rev){
$query = 'SELECT *'
.' FROM '.$this->myTableName
.' WHERE PartNumber = ?'
.' AND CustomerNumber = ?'
.' AND Rev = ?';
$conn = (new DBConnector)->connect();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$statement = $conn->prepare($query);
//var_dump($statement);
//var_dump($query);
//var_dump($conn);
$statement->bind_param('sis', $partNumber, $customerNumber, $rev);
$statement->execute();
$result = $statement->get_result();
var_dump($result);
//var_dump($statement);
//var_dump($customerNumber);
//var_dump($rev);
if ($result->num_rows == 1) {
// output data of each row
$this->Properties = $result->fetch_assoc();
var_dump($this->Properties);
$conn->close();
return true;
} else {
$this->Properties = [];
$conn->close();
return false;
}
}
I am getting the following error, When I tried to execute GET_Card_TRANS procedure:
[code] => 6550
[message] => ORA-06550: line 6, column 21:
PLS-00103: Encountered the symbol "" when expecting one of the following:
. ( ) , * # % & = - + < / > at in is mod remainder not rem =>
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec between || indicator multiset member submultiset
[offset] => 155
[sqltext] => BEGIN
WEB_SHOW.GET_Card_TRANS(
:User_Id,
:Pswd,
:vcard_id
:sdate
:EDATE
:Vcond
:CARD_TRANS_data
);
END;
This is the PHP code:
<?php
// Connect to database
$conn = oci_connect("xxx", "yyy", "aaaa:bb/cc", 'dd');
if (!$conn) {
$e = oci_error($conn);
print_r($e);
exit ("Connection failed.");
}
$user_id = 'demo';
$password = 'password';
$vcard_id = '1-0';
$start_date = '01-01-2016';
$end_date = '01-01-2016';
$condition = '1';
$sql = "BEGIN
web_show.GET_Card_TRANS(
:User_Id,
:Pswd,
:vcard_id
:sdate
:EDATE
:Vcond
:CARD_TRANS_data
);
END;";
$stmt = oci_parse($conn, $sql);
oci_bind_by_name($stmt, ':User_Id', $user_id );
oci_bind_by_name($stmt, ':Pswd', $password );
oci_bind_by_name($stmt, ':vcard_id', $vcard_id );
oci_bind_by_name($stmt, ':sdate', $start_date );
oci_bind_by_name($stmt, ':EDATE', $end_date );
oci_bind_by_name($stmt, ':Vcond', $condition );
// Create a new cursor resource
$curs = oci_new_cursor($conn);
// Bind the cursor resource to the Oracle argument
oci_bind_by_name($stmt,":CARD_TRANS_data",$curs,-1,OCI_B_CURSOR);
if (!oci_execute($stmt)) {
$e = oci_error($stmt);
print_r($e);
exit("Procedure Failed.");
}
// Execute the cursor
if (!oci_execute($curs, OCI_DEFAULT)) {
$e = oci_error($curs);
print_r($e);
exit("Execute cursor Failed.");
}
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
print_r($row);
//echo $row['FIRST_NAME'] . "<br />\n";
}
oci_free_statement($stmt);
oci_free_statement($curs);
oci_close($conn);
?>
Missing commas, perhaps?
This:
$sql = "BEGIN
web_show.GET_Card_TRANS(
:User_Id,
:Pswd,
:vcard_id
:sdate
:EDATE
:Vcond
:CARD_TRANS_data
);
END;"
;
Should instead be:
$sql = "BEGIN
web_show.GET_Card_TRANS(
:User_Id,
:Pswd,
:vcard_id,
:sdate,
:EDATE,
:Vcond,
:CARD_TRANS_data
);
END;";
In my query the update statement doesn't work, the error given is:
Number of parameter doesn't match with prepared statement
this is my code:
public function update_resource($resource)
{
$mysqli = new MySQLi(HOST, USERNAME, PASSWORD, DATABASE);
$this->connection_state($mysqli);
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
AND sigla = '$sigla' AND colore = '$colore' AND planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param("ssssi", $descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}
The code go into the Added condition but the query fail, what's the problem?
public function update_resource($resource)
{
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
, sigla = '$sigla', colore = '$colore', planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param($descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}?
Your problem is that you don't have any placeholders in your query.
Refer to manual to see how placeholders should be set.
In general, placeholders are ? which later will be replaced with values, so your query should look like:
$query = "UPDATE risorse SET descrizione = ?
AND sigla = ? AND colore = ? AND planning = ?
WHERE id = ?";
please visit on http://php.net/manual/en/pdostatement.bindparam.php.you got your answer.see Example #1 Execute a prepared statement with named placeholders
Here's the code:
<?php
$sql = mysql_query($db, "CALL selectproducts()");
if( $sql === FALSE ) {
die('Query failed returning error: '. mysql_error());
} else {
while($row=mysql_fetch_array($sql))
{
$id=$row['prodname'];
$name=$row['proddescription'];
$desc=$row['prodsupplier'];
$supp=$row['proddate'];
$date=$row['prodprice'];
$qtyleft=$row['prodquantity'];
Getting this Error:
Warning: mysql_query() expects parameter 2 to be resource, string given in C:\xampp\htdocs\inventory\tableedit.php on line 166
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in C:\xampp\htdocs\inventory\tableedit.php on line 170
Why is it has errors when in fact i have no parameters in call procedure?
Should be:
mysql_query("CALL selectproducts()", $db);
Documentation
Note that the mysql_ functions are now depreciated.
Try this method:
<?php
$link = mysqli_init();
mysqli_options($link, MYSQLI_INIT_COMMAND, "SET AUTOCOMMIT=0");
mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
mysqli_real_connect($link, $hostname, $username, $password, $dbName);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "CALL simpleproc()";
if (mysqli_real_query($link,$query)) {
if ($result2 = mysqli_store_result($link)) {
while ($row = mysqli_fetch_assoc($result2)) {
$q = $row["login"];
echo $q;
}
}
}
mysqli_close($link);
?>
I do believe you're getting your mysql_query arguments getting mixed up, where was $db is the second parameter, and the first is the MySQL query to be executed.
Although furthermore, you're probably better off using mysqli instead for future proofing:
<?php
$mysqli = new mysqli('username', 'username', 'password', 'database' );
$result = $mysqli->query("CALL selectproducts()");
if( !$result ) {
die('Query failed returning error: '. $mysqli->connect_errno );
} else {
while( $row = $result->fetch_array(MYSQLI_ASSOC)) {
$id = $row['prodname'];
$name = $row['proddescription'];
$desc = $row['prodsupplier'];
$supp = $row['proddate'];
$date = $row['prodprice'];
$qtyleft = $row['prodquantity'];
}
}
?>
From checking the mysqli PHP Docs for calling stored procedure:
<?php
/**
* Prepare Stored Procedure
**/
if (!($result = $mysqli->prepare("CALL selectproducts()"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$result->execute()) {
echo "Execute failed: (" . $result->errno . ") " . $result->error;
}
/**
* Iterate through each result
**/
do {
if ($res = $result->get_result()) {
printf("---\n");
var_dump(mysqli_fetch_all($res));
mysqli_free_result($res);
} else {
if ($result->errno) {
echo "Store failed: (" . $result->errno . ") " . $result->error;
}
}
} while ($result->more_results() && $result->next_result());
?>