PHP/MySQL SET var = var - var - php

I made a shop for my site, and got it working but realized it was lacking the ability to properly buy an item. to put it into perspective, you don't walk into a store, grab an item, buy it, grab it again, buy it, grab it again, etc. to get as many as you want. you grab them all at once. my site is lacking such feature. So, I have attempted to change the code that takes the stock, and so far am not succeeding.
I've tried the following:
function takestock($id, $count) {
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."shop
SET stock = stock - ?
WHERE
id = ?");
$stmt->bind_param("ii", $id, $count);
$result = $stmt->execute();
$stmt->close();
return $result;}
and
function takestock($id, $count) {
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."shop
SET stock = stock - $count
WHERE
id = ?");
$stmt->bind_param("ii", $id, $count);
$result = $stmt->execute();
$stmt->close();
return $result;}
and
function takestock($id, $count) {
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."shop
SET stock = stock - ".$count."
WHERE
id = ?");
$stmt->bind_param("ii", $id, $count);
$result = $stmt->execute();
$stmt->close();
return $result;}
but I cant seem to take the count away from the stock!

The order that you bind parameters should correspond to the order you want to use them in your SQL statement. Here, the item count should come first and the id second. I.e., replace the following line:
$stmt->bind_param("ii", $id, $count);
With:
$stmt->bind_param("ii", $count, $id);

Related

INSERT INTO doesn't fill all rows

I have a problem with my code, it is PayPal express Integration. I mean in its original state after some tweaking to match my database and so on it works, it fills rows with ex. payerID and so on.
I have in my database 2 tables - first is Products it has 5 Rows, like productID, Price, currency and so on, but I need 1 extra row - let's say we call it Credits. I manually added it to my database, filled Table Products with data.
Then I have another table called Orders- where I added Row called Credits too, than after successful payment+checkout matched Credits to chosen Product it should fill this Row Credits in Orders table. The problem that I have it that Order Table is filled with all data except that last Row -> Credits it's always showing NULL in the database.
This is part of my code:
public function getAllProducts()
{
$db = getDB();
$stmt = $db->prepare("SELECT * FROM products");
$stmt->bindParam("pid", $pid, PDO::PARAM_INT) ;
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db=null;
return $data;
}
public function getProduct($pid)
{
$db = getDB();
$stmt = $db->prepare("SELECT * FROM products WHERE pid=:pid");
$stmt->bindParam("pid", $pid, PDO::PARAM_INT) ;
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_OBJ);
$db=null;
return $data;
}
and this where I have a problem
public function orders()
{
$id = $_SESSION['session_id'];
$db = getDB();
$stmt = $db->prepare("SELECT P.product, P.price, P.product_img, P.currency, P.credits, O.created, O.oid FROM orders O, products P WHERE O.id_fk=:id AND P.pid = O.pid_fk ORDER BY O.created DESC");
$stmt->bindParam("id", $id, PDO::PARAM_INT) ;
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db=null;
return $data;
}
public function updateOrder($pid, $payerID, $paymentID, $token, $credits)
{
$id = $_SESSION['session_id'];
if($this->pyamentCheck($paymentID) < 1 && $id > 0){
$db = getDB();
$stmt = $db->prepare("INSERT INTO orders (id_fk, pid_fk, payerID, paymentID, token, created, credits) VALUES (:id, :pid, :payerID, :paymentID, :token, :created, :credits)");
$stmt->bindParam("paymentID", $paymentID, PDO::PARAM_STR) ;
$stmt->bindParam("payerID", $payerID, PDO::PARAM_STR) ;
$stmt->bindParam("token", $token, PDO::PARAM_STR) ;
$stmt->bindParam("pid", $pid, PDO::PARAM_INT) ;
$stmt->bindParam("id", $id, PDO::PARAM_INT) ;
$created = time();
$stmt->bindParam("created", $created, PDO::PARAM_INT) ;
$stmt->bindParam(":credits", $credits, PDO::PARAM_INT) ;
$stmt->execute();
$db=null;
return true;
}
else{
return false;
}
}
I canĀ“t figure it out.
This is quite a frequent question so it deserves an answer, however obvious it may seem.
Once you have a working INSERT query and one of columns turns to be NULL, it means that the source variable contained NULL.
So the problem is neither with PDO, nor prepared statements, nor a database but simply with your source variable, $credits. You have to check your code related to this variable and make sure it does contain the desired value.

Property access is not allowed yet in

I have one simple function for delete account from my database. I have written it like below
public function removeAccount($email) {
$response = array('code' => 0, 'error' => false);
$stmt = $this->conn->prepare("SELECT id FROM user WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows) {
$user = $result->fetch_assoc();
$id = $user['id'];
$stmt->close();
$stmt = $this->conn->prepare("DELETE FROM number_list WHERE user_id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$stmt = $this->conn->prepare("DELETE FROM number_status WHERE user_id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$stmt = $this->conn->prepare("INSERT INTO old_user(email,serial,premium) SELECT email, device_id, membership FROM user WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
$stmt = $this->conn->prepare("DELETE FROM user WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();
if ($stmt->affected_rows) {
$response["code"] = 1;
}
}
return $response;
}
Its giving me warning in below line
if ($stmt->affected_rows) {
I have searched way for solve it but does not getting idea whats wrong and what can fix it. Please check and let me know if someone can have idea about it. Thanks a lot.
$stmt = $this->conn->prepare("DELETE FROM user WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
if($stmt->affected_rows > 0) { $response["code"] = 1; }
$stmt->close();
In this case, we checked to see if any rows got updated. For reference, here's the usage for mysqli::$affected_rows return values.
-1 - query returned an error; redundant if there is already error handling for execute()
0 - no records updated on UPDATE, no rows matched the WHERE clause or no query has been executed
Greater than 0 - returns number of rows affected; comparable to mysqli_result::$num_rows for SELECT
You're trying to get the number of affected rows from a closed statement.
Instead of
$stmt->execute();
$stmt->close();
if ($stmt->affected_rows) {
$response["code"] = 1;
}
Use
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
if ($num_affected_rows) {
$response["code"] = 1;
}
There are many reasons for this error, but the one I had today was one I have not found documented anywhere.
I had two (2) copies of same virtual machine running and they were both competing in some way that I do not understand well enough to explain, but going into VirtualBox and shutting one of them off solved the problem.
I know this an obscure scenario, but if anyone else runs across the same I hope my answer stops them from wasting time on it like I did.

SQL statement inside while loop PHP

I am trying to run a SQL statement within a while loop, using the variable $id set in the previous statement but am struggling to get it working. If I remove the statement in the while loop I can see the while loop is functioning as it displays the $id variable multiple times:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
echo "ID: " . $id . "<br>";
}
However when I add the SQL statement back in, I am presented with only the first $id result. If I add in $stmt->close(); at the start of the while loop I do get the first company name, but then the while loops ends. Here is the code:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
Any ideas please?
Update: If I add in a store result before the loop and free result inside the loop I get the first company name and also get the "finished loop" echo:
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
$stmt->store_result();
while ($stmt->fetch()) {
$stmt->free_result();
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
echo "finished the loop";
}
Thanks.
Cant comment so answering here.
I think you need to use $stmt->bind_param("s", $businessPark); instead of $stmt->bind_param("s", $num);
I had it working (albeit with different queries) on my test server - I'm pretty sure the issue is that you need to pass the resultset through to PHP so that you can prepare the second statement (which must be outside the loop) - otherwise sql = $conn->prepare( ... ); fails and returns false.
This should work:
$businessPark = $_SESSION['businessPark'];
$num = "1";
//first statement
$stmt = $conn->prepare("SELECT CompanyId from Portal.services WHERE ".$businessPark." = ?");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($id);
//pass the result to PHP so you can prepare a new statement
$stmt->store_result();
//second statement
$sql = $conn->prepare("SELECT CompanyName from phpipam.ipaddresses WHERE id = ?");
while ($stmt->fetch()) {
$sql->bind_param("s", $id);
$sql->execute();
$sql->bind_result($CompanyName);
$sql->fetch();
echo $CompanyName;
}
//clean up
$stmt->free_result();
$stmt->close();
You can accomplish what you want with a join. I know that this does not answer why your code is not working but in my opinion it's a better solution anyway.
$businessPark = $_SESSION['businessPark'];
$num = "1";
$stmt = $conn->prepare("
SELECT t2.CompanyName
FROM Portal.services t1
INNER JOIN phpipam.ipaddresses t2 ON t1.CompanyId = t2.id
WHERE " . $businessPark . " = ?
");
$stmt->bind_param("s", $num);
$stmt->execute();
$stmt->bind_result($companyName);
More information about join syntax

Processing SQL query result in PHP, then inserting again within same function

I'm trying to make a function work, where I ask for a number of free seats left in a car, and if executed, it subtracts 1 from the result and updates the cell in database.
Sql statements must be correct... am I missing out on anything else?
function seatCalc($id){
$stmt=$this->connection->prepare("SELECT seats_left FROM drive WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->bind_result($seat_count);
$stmt->execute();
return $seat_count;
if($seat_count >= 1){
$seat_count -= 1;
$stmt=$this->connection->prepare("UPDATE drive SET seats_left=? WHERE id=?");
$stmt->bind_param("ii", $seat_count, $id);
$stmt->execute();
}
}
It's a part of my university project and unfortunately, I can't reach my professor at the moment.
Thank you in advance!
Your return statement breaks you out of the function before the if block gets processed.
your condition is incorrect;
you have unreached statements after return;
Here is code:
function seatCalc($id){
$stmt=$this->connection->prepare("SELECT seats_left FROM drive WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->bind_result($seat_count);
$stmt->execute();
if($seat_count > 0){
$stmt=$this->connection->prepare("UPDATE drive SET seats_left=seats_left-1 WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
}
return $seat_count;
}
Also you can substract one with database..
Oh boy
function seatCalc($id){
$stmt=$this->connection->prepare("SELECT seats_left FROM drive WHERE id=:i");
$stmt->bind_param(":i", $id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$seat_count = intval($row['seats_left']);
if($seat_count > 0){
$seat_count -= 1;
$stmt=$this->connection->prepare("UPDATE drive SET seats_left=seats_left-1 WHERE id=:id");
$stmt->bind_param(":id", $id);
$stmt->execute();
}
return $seat_count;
}

Problem with mysqli fetch

I'm having a mysqli data fetching problem. I will try to explain my problem by example:
I want to fetch entries (by different persons), from a table. Now I want to look for each of the fetched person's name in another table and see if he has any photo.
My code is given below, however its not working, I'm getting following errors:
mysqli::prepare() [mysqli.prepare]: All data must be fetched before a new statement prepare takes place
Call to a member function fetch() on a non-object in ...
My Code:
if ($stmt = $this->mysqli->prepare("SELECT entry, author, time FROM messages WHERE user = ?")) {
$stmt->bind_param("s", $user_name);
$stmt->execute();
$stmt->bind_result($entry, $author, $time);
while ($stmt->fetch()) {
if ($stmt = $this->mysqli->prepare("SELECT photo_id FROM photos WHERE user = ?")) {
$stmt->bind_param("s", $author);
$stmt->execute();
$stmt->bind_result($photo_id);
}
//echo $photo_id;
}
$stmt->close();
}
I'll be very thankful for any help.
Assign the second statement to new variable so it wouldn't override the first variable and cause the "all data must be fetched.." error.
if ($stmt = $this->mysqli->prepare("SELECT entry, author, time FROM messages WHERE user = ?")) {
$stmt->bind_param("s", $user_name);
$stmt->execute();
$stmt->bind_result($entry, $author, $time);
while ($stmt->fetch()) {
if ($st = $this->mysqli->prepare("SELECT photo_id FROM photos WHERE user = ?")) {
$st->bind_param("s", $author);
$st->execute();
$st->bind_result($photo_id);
}
//echo $photo_id;
$st->close();
}
$stmt->close();
}

Categories