I'm attempting to run both query to different table.
As tbl_invoice are inserted, invoice_id is created from first query (first one works) but when I put another query for tbl_invoice_details I think it doesn't actually pass the previous invoice_id value, tried with if($invoice_id != null){...} but this query doesn't seem to work for tbl_invoice_details.
Any help would be appreciated, thanks.
include_once 'connectdb.php';
$id = $_GET['id'];
$select = $pdo->prepare("SELECT * FROM tbl_product WHERE barcode=$id");
$select->execute();
$row = $select->fetch(PDO::FETCH_OBJ);
// FOR TBL_INVOICE
$variables
...
$insert = $pdo->prepare("INSERT INTO tbl_invoice(customer_name,order_date,subtotal,tax,discount,total,paid,due,payment_type,profit) values(:cust,:orderdate,:stotal,:tax,:disc,:total,:paid,:due,:ptype,:profit)");
$insert->bindParam(':cust',$customer_name);
$insert->bindParam(':orderdate',$order_date);
$insert->bindParam(':stotal',$subtotal);
$insert->bindParam(':tax',$tax);
$insert->bindParam(':disc',$discount);
$insert->bindParam(':total',$total);
$insert->bindParam(':paid',$paid);
$insert->bindParam(':due',$due);
$insert->bindParam(':ptype',$payment_type);
$insert->bindParam(':profit',$profit);
$insert->execute();
// FOR TBL_INVOICE_DETAILS
$invoice_id = $pdo->lastInsertId();
if($invoice_id != null){
$rem_qty = $stock - $qty;
$update = $pdo->prepare("UPDATE tbl_product SET pstock='$rem_qty' WHERE barcode='".$id."'");
$update->execute();
$insert = $pdo->prepare("INSERT INTO tbl_invoice_details(invoice_id,product_id,product_name,qty,price,order_date,values(:invid,:pid,me,:qty,:price,:orderdate,:profit)");
$insert->bindParam(':invid',$invoice_id);
$insert->bindParam(':pid',$pid);
$insert->bindParam(':pname',$productname);
$insert->bindParam(':qty',$qty);
$insert->bindParam(':price',$total);
$insert->bindParam(':orderdate',$order_date);
$insert->bindParam(':profit',$profit);
$insert->execute();
}
?>```
enable PDO error reporting:
include_once 'connectdb.php';
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = $_GET['id'];
when a SQL error occurs, it will get thrown as an exception. if we don't enable PDO error reporting, then the code needs to check the return from each SQL call to see if an error occurred.
The question here isn't "how to get multiple SQL query to different table". The real question is "how do I see what SQL error occurred".
Related
DB Type: MariaDB
Table Engine: InnoDB
I have a table where inside it has a column with a value which is being incremented (not auto, no inserting happens in this table)
When I run the following SQL query in phpMyAdmin it works just fine as it should:
UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc';
SELECT LAST_INSERT_ID();
The above returns me the last value for the my_column table when the query happened. This query was taken directly from the mysql docs on locking: https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html (to the bottom) and this seems to be the recommended way of working with counters when you don't want it to be affected by other connections.
My PDO:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc';
SELECT LAST_INSERT_ID();";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
$result = $stmt->fetchColumn(); // causes general error
$result = $stmt->fetch(PDO::FETCH_ASSOC);// causes general error
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Exact error SQLSTATE[HY000]: General error, If I remove the lines where I try to get the result, it updates the column, but I still do not have a return result... how do I perform that update query and get the select result all in one go like I do when I run it in phpMyAdmin? This all needs to happen in one go as specified by the MySQL docs so I don't have issues where two connections might get the same counter.
There is no need to perform SELECT LAST_INSERT_ID();. PDO will save that value automatically for you and you can get it out of PDO.
Simply do this:
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8mb4", $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$sql = "UPDATE `my_table`
SET `my_column` = LAST_INSERT_ID(`my_column` + 1)
WHERE `my_column2` = 'abc'";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
$newID = $conn->lastInsertId();
lastInsertId() will give you the value of the argument evaluated by LAST_INSERT_ID().
<?php
try
{
global $db;
$user = 'postgres';
$password = '*****'; //For security
$db = new PDO('pgsql:host=localhost;dbname=dnd', $user, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $ex)
{
echo 'ERROR!!: ' . $ex->getMessage();
die();
}
$table = htmlspecialchars($_REQUEST['table']);
$idNum = htmlspecialchars($_REQUEST['id']);
try {
//$query = "SELECT * FROM $table WHERE id = $idNum"; This works
//$query = "SELECT * FROM $table WHERE id = :number"; This works
$query = "SELECT * FROM :tableName WHERE id = :number";
$statement = $db->prepare($query);
$statement->bindValue(":tableName", $table, PDO::PARAM_STR);
$statement->bindValue(":number", $idNum, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $excep) {
echo "Opps: " . $excep->getMessage();
die();
}
Okay I'm going crazy here trying to get this to work.
I have a database set up that I need to query from. I receive the query from an AJAX request with the name of the table I want and the id for the item. When I try to query with both variables, the binding does not occur in the prepared statement and instead I get this error code
Opps: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "$1" LINE 1: SELECT * FROM $1 WHERE id = 1 ^
When I have just the straight PHP variables it works fine so I know it can work, but when I want to bind multiple it seems to fail and give a variable number as above.
I can also get it to work if I simply have one of the variables bound, such as the second commented out query in the code - this only works tho if I have the variable I want at the end and not if I wanted to lookup the table spot. (I.E.
$query = "SELECT * FROM :tableName WHERE id = $idNum"; does not work)
I need to cleanse the variables to prevent SQL injection, but I can't do that without binding the variables in a prepared statement. Any help would be appreciated!
According to the PHP manual you can't bind a tablename. As you mentioned it, you can replace it by a variable, but you can't replace it with a placeholder.
So the only solution that will work for you is the query you have above:
$query = "SELECT * FROM $table WHERE id = :number"
This will be what you're looking for. If you want to make it safe for injection, you have to find another way. (Regex for example).
Ref: http://us3.php.net/manual/en/book.pdo.php#69304
I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.
Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style?
I have tried to apply it to my code but I am still not getting the right response.
if($data->edit_flag == 'ADDED')
{
$rowdata[0] = $data->location_name;
$rowdata[1] = 0;
$rowdata[2] = $data->store_id;
$query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = mysqli_stmt_insert_id($statement);
echo "inserted id: " . $id;
}
I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following
$id = $conn->lastInsertId();
echo "insert id: " . $id;
but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:
$statement = $conn->prepare($query);
$statement->execute($rowdata);
You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = $conn->lastInsertId();
Some potential reasons why it is not working:
Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.
Hope this helps!
If you are using pdo,
$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();
I have the following query
$products = $this->mysqliengine->query("select * from temp_all_product where download_status = 0") or die($this->mysqliengine->error());
$temp_status_update = $this->mysqliengine->prepare("update temp_all_product set download_status = ? where id = ?") or die($this->mysqliengine->error);
$temp_status_update->bind_result($download_status, $id);
while($product = $products->fetch_assoc()) {
$id = $product['id'];
$download_status = 1;
$temp_status_update->execute();
}
In the above statement I can select the values from temp table but unable to update the status. What is the problem here
You need to use bind_param in your update statement instead of bind_result.
$temp_status_update->bind_param('dd', $download_status, $id);
The 'dd' just tells the system that each input is a number.
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
#eggyal was merely suggesting that you could replace all your code with a single update statement. Your remark about LIMIT does not make much sense.
Suggestion: If you don't have much invested in mysqli then switch to PDO. It allows using named parameters which can make your code more robust and easier to maintain:
$sql = "UPDATE temp_all_product SET download_status = :status where id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute(array('status' => 1, 'id' => $product['id']));
Plus you can configure it to throw exceptions so you don't need all this error checking.
http://www.php.net/manual/en/book.pdo.php
http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/
I have a database table and i am updating the table columns this way.
$mysqli = new mysqli('localhost', 'root', '', 'db');
if (mysqli_connect_errno()) {
echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
return 'error';
}
$username = $data['username'];
$data['image'] = $this->replace_whitespace($data['image']);
foreach($data as $key=>$value){
$this->query = "UPDATE users SET $key=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if($this->statement){
$this->statement->bind_param('s', $value);
$this->statement->execute();
$this->statement->close();
}
}
Is it possible to update more than one table columns in one go. I tried this but in-vain.
$this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if($this->statement){
$this->statement->bind_param('sss', $value1, $value2, $value3);
$this->statement->execute();
$this->statement->close();
}
Is there a better way doing this?
$mysqli = new mysqli('localhost', 'root', '', 'db');
if (mysqli_connect_errno()) {
echo 'failed to connect to db.. <br>' . mysqli_connect_errno();
return 'error';
}
$username = $data['username'];
$this->query = "UPDATE users SET fname=?, lname=?, email=?, tpin=?, image=?, address=? country=?, city=?, state=?, postal=? WHERE username='$username'";
$this->statement = $mysqli->prepare($this->query);
if ($this->statement) {
$this->statement->bind_param('ssssssssss', $data['fname'],$data['lname'],$data['email'],$data['tpin'], $data['file'], $data['address'],$data['country'],$data['city'],$data['state'], $data['post_code']);
$this->statement->execute();
$this->statement->close();
}
This is my real code.
Remove the "," after col3=?
This will fix the syntax error
$this->query = "UPDATE users SET col1=?, col2=?, col3=?, WHERE username='$username'";
You have an extra comma, meaning your SQL is reading "WHERE" as another column and everything gets messed up.
$this->query = "UPDATE users SET col1=?, col2=?, col3=? WHERE username='$username'";
Should work fine.
In response to the comment below, this is the correct way of going about it, so it must be a faulty variable somewhere, what error messages are you getting? (If any)
It could also be that one of the parameters you are binding is not a string. Regardless, we'd need a more in-depth example.
Is it possible to update more than one table columns in one go
Yes. Actually, updating many fields in one query is a very core feature of any DBMS. You can always expect it to be supported.
I tried this but in-vain.
Well, you have to try more, like we all do. After all, it's your job.
Two notes regarding your "real" code:
You have to bind ALL variables in the query, not only some of them
you have to configure mysqli to report errors:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I assume it works the same way as putting new values into the database.
Update a row mysql in php