Function won't select data from database - php

I'm working on a new website at the moment and I have a bit of a problem.
I look if an item exist, if it does, it will execute an insert query. The insert query works but the problem is that the select query doesn't work
Class
public function doubt($event_id)
{
$exist = $this->conn->prepare("SELECT * FROM agenda WHERE id=?");
$exist->bind_param('s', $event_id);
$exist->execute();
$exist->get_result();
if($exist->num_rows != null)
{
$now = new DateTime();
$date = $now->getTimestamp();
$status = 2;
$stmt = $this->conn->prepare("INSERT INTO absence (user_id,event_id,status,ip,date) VALUES (?, ?, ?, ?, ?) ");
$stmt->bind_param('sssss', $_SESSION['user_session'], $event_id, $status, $_SERVER['REMOTE_ADDR'], $date);
$stmt->execute();
$stmt->close();
return true;
}
else
{
return false;
}
}

Related

How to update an array using PHP

I have an app that is written using procedural PHP. I've created an insert page where I take a buck of addresses and pass them as an array and insert them in the database. There I have the id of the row and then an orderId, the address type, and the address. Now I want to be able to update a specific one. Until now I've come up with the following:
// update new supplier order
function updateSupplierOrder($conn, $orderDate, $datePickup, $dateDelivery, $timePickup, $timeDelivery, $car, $carType, $goodsDescription, $paletChange, $paletNo, $supplier, $orderObservation, $paymentDate, $value, $addressPickup, $addressDelivery, $userid, $orderID) {
$sql1 = "UPDATE suppliersOrders SET supplierId = ?, date = ?, datePickup = ?, timePickup = ?, goodsDescription = ?, dateDelivery = ?, timeDelivery = ?, carType = ?, carNo = ?, paletChange = ?, paletNo = ?, value = ?, invoice = ?, observations = ?, operator = ? WHERE id = ?;";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header ("location: ../suppliersOrders?error=failedupdateorder");
exit();
}
mysqli_stmt_bind_param($stmt1, "isssssssisisssii", $supplier, $orderDate, $datePickup, $timePickup, $goodsDescription, $dateDelivery, $timeDelivery, $carType, $car, $paletChange, $paletNo, $value, $paymentDate, $orderObservation, $userid, $orderID);
mysqli_stmt_execute($stmt1);
mysqli_stmt_close($stmt1);
for ($i=0; $i<count($addressPickup); $i++) {
$address = $addressPickup[$i];
$type = '1';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
for ($i=0; $i<count($addressDelivery); $i++) {
$address = $addressDelivery[$i];
$type = '2';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
header("location: ../suppliersOrders-edit.php?id=$orderID");
}
But this will update all the addresses of an order and a type. How can I update based on the id from the table, this will make sure that the right address is updated.
Help would be appreciated.
I found a solution to the issues. The simplest way to be able to update the row that I needed was to add the id value from the row in an array and do the update based on the WHERE clause that had the id value. This way I was able to update just the needed value/row.

MySql Insert returns null

i have the following function:
public function insertMomentToDB($uid, $type, $data)
{
$stmt = $this->conn->prepare("INSERT INTO moments_newsfeed(user_id, type, time, data) VALUES(?, ?, NOW(), ?)");
$stmt->bind_param("sss", $uid, $type , $data);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result)
{
return true;
}
else
{
return false;
}
}
where $data = json undecoded, i want to put it in json format inside the table
$result is always null so it returns false..

PHP prepared statement doesn't work with intval()

Please look my code:
$insertStmt = $conn->prepare("INSERT INTO orders (OrderID, OrderTrackingNumber, OrderTotal, CustomerID) VALUES (?, ?, ?, ?)");
$insertStmt->bind_param("ssdi", $orderID, strval("Not Ship Yet"), $orderTotal, $userID);
if ($insertStmt->execute()) {
$insertStmt = $conn->prepare("INSERT INTO ordersproducts (OrderID, ProductID, ProductSold) VALUES (?, ?, ?)");
$updateStmt = $conn->prepare("UPDATE products SET ProductQuantity = ? WHERE ProductID = ?");
foreach ($orderedProducts as $orderedProduct) {
$productQuantity = intval($orderedProduct->ProductQuantity) - intval($orderedProduct->ProductAddedQuantity);
$insertStmt->bind_param("sii", $orderID, intval($orderedProduct->ProductID), intval($orderedProduct->ProductAddedQuantity));
$updateStmt->bind_param("ii", intval($productQuantity), settype($orderedProduct->ProductID, "integer"));
if ($insertStmt->execute() && $updateStmt->execute()) {
if ($updateStmt->affected_rows == 1) {
$isSuccefull = TRUE;
} else {
$isSuccefull = FALSE;
break;
}
} else {
$isSuccefull = FALSE;
echo $insertStmt->error . " | " . $updateStmt->error;
break;
}
}
}
At the line of $updateStmt->bind_param, if I convert $orderedProduct->ProductID to int by intval($orderedProduct->ProductID), the updateStmt will not work ($updateStmt->affected_rows = 0). However, I use settype($orderedProduct->ProductID, "integer"); then it will work like a champ. And only this place gets that issue; others work very well.
Why?
Thanks for helping me.

How to insert with a foreign key in the child table php

I have two tables users And requests. Users table has columns: id, username, password and town. I can insert data in users successfully. requests table has: id, user_id, product_name, proposed_price and request_description, where user_id is a foreign key referencing to id from users table. The problem is that insert data fails in requests table which has user_id as a foreign key. I get an error:
Undefined variable: user_id and mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement on line : $qry->bind_param("i", $user_id);
This function is supposed to be used in insertion:
public function User_request ($product_name, $proposed_price, $request_description) {
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' ");
$qry->bind_param("i", $id);
$result= $qry->execute();
$user_id = $qry->num_rows();
$qry->close();
if($user_id > 0){
$stmt = $this->conn->prepare("INSERT INTO requests (user_id, product_name, proposed_price, request_description) VALUES(?, ?, ?, ?)");
$stmt->bind_param("sss",$user_id, $product_name, $proposed_price, $request_description);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM requests WHERE request_description = ?");
$stmt->bind_param("s", $request_description);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
And below code calls above function:
<?php
include './DbHandler.php';
$db = new DBHandler();
// json response array
$response = array("error" => FALSE);
if ( isset($_POST['product_name']) && isset($_POST['proposed_price']) && isset($_POST['request_description']) ) {
// receiving the post params
$product_name = $_POST['product_name'];
$proposed_price =$_POST['proposed_price'];
$request_description =$_POST['request_description'];
// create a new request
$user = $db-User_request($product_name, $proposed_price, $request_description);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["user"]["username"] = $user["username"];
$response["user"]["proposed_price"] = $user["proposed_price"];
$response["user"]["request_description"] = $user["request_description"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "oops error occured!";
echo json_encode($response);
}
}
else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters are missing!";
echo json_encode($response);
}
?>
Rewrite User_request() function accordingly:
public function User_request ($product_name, $proposed_price, $request_description) {
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = ? ");
$qry->bind_param("i", $user_id);
$result= $qry->execute();
$user_id = $qry->num_rows();
$qry->close();
if($user_id > 0){
$stmt = $this->conn->prepare("INSERT INTO requests (user_id, product_name, proposed_price, request_description) VALUES(?, ?, ?, ?)");
$stmt->bind_param("isss", $user_id, $product_name, $proposed_price, $request_description);
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM requests WHERE request_description = ?");
$stmt->bind_param("s", $request_description);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return false;
}
}
}
Note: You supposed to use placeholder ? in prepare statement: $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' "); in place of '$user_id', since you have $qry->bind_param("i", $user_id).
Similar error in $stmt->bind_param("sss",$user_id, $product_name, $proposed_price, $request_description);, replace "sss" with "isss".
You are looking for the string literal of '$user_id' here.
$qry = $this->conn->prepare("SELECT id FROM users WHERE id = '$user_id' ");
This is probably not what you want. You are also using named placeholders that are nowhere to be found in your query. I suggest reviewing the PDO docs.

Mysqli INSERT command followed by an UPDATE

I would like to have data inserted in one table, and data updated in another through prepared statements in mysqli. Trying the following only executes the INSERT command:
EDITED:
if($stmt=$mysqli->prepare("SELECT bids_id, bid, fruit_volume FROM basket ORDER BY bid DESC")) {
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($bids_id, $bid, $fruit_volume);
while($stmt->fetch()) {
$stack = array($bids_id, $bid, $fruit_volume);
array_push($all_fruits, $stack);
}
$stmt->free_result();
}
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii', 800, 1);
$stmt3->execute();
}
}
$mysqli->close();
bind_param passes by reference not by value,so you need to have those values in variables before they can be referenced
$a=800;
$b=1;
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii',$a, $b);
$stmt3->execute();
}
}
Try this instead
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii', 800, 1);
$stmt3->execute();
}
}
$mysqli->close();

Categories