basically, I used a query to move the data (userid to QTY) from another table (cart) to this table shown below (cart2). After that, i will then insert two sets of data invoice_id and date into the database based on the ord_id.
Below is my database:
From the image, I've tried inserting the data and only the 1st row worked. Subsequent row does not get the subsequent data i inserted.
Here is the code:
$user= $_SESSION['id'];
$trx_id = $_GET['tx'];
$date = date("Y-m-d") ;
Move data from cart to cart2
$move_cart = $db->prepare("INSERT INTO cart2(userid,Product_ID,Product_name,Price,QTY)
SELECT userid,Product_ID,Product_name,Price,QTY FROM cart WHERE userid=?");
$move_cart->bind_param("s",$user);
If it succeeded, delete data from cart
if ($move_cart->execute()) {
$delete_cart =$db->prepare("delete from cart where userid =?");
$delete_cart->bind_param("s", $user);
$delete_cart->execute();
}
> insert data(trx_id and date) to cart 2 based on ord_id
$sql="SELECT * FROM cart2 ";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$ord = $row['ord_id'];
$update_cart = $db->prepare("UPDATE cart2 SET invoice_id =?,date =? WHERE ord_id =?");
$update_cart->bind_param("ssi",$trx_id,$date,$ord);
$update_cart->execute();
$ord ++;
The error is probably in the last piece of code. other codes are just for referencing.
Related
Hello i have a posts_comments table in my phpmyadmin,
and i can see that when i loop out the comments and send the notifications to users who commented then am getting the repeated details which is sending duplicate comments instead of one comment per user_id.
$sql = "SELECT * FROM posts_comments WHERE id=?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$_GET['id']);
$rows = $stmt->fetchAll();
foreach($rows as $row){
$commenter_id = $row['user_id'];
//Inserting a notifation to all users who comments
$insert = "INSERT INTO notifications(message,user_id)VALUES(?,?)";
$stmt = $this->connect()->prepare($insert);
$stmt->execute('some has commented on a post you are following', $logged_user);
}
Please help me send only one notification per user in posts_comments
Try using distinct keyword. It will eliminate all the duplicate records and fetching only unique records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
I created a matching game and stored it score in the database. So every time a user finishes the game, his score is updated in the database replacing the old score.The problem is, I wanted to add the new score with the old score and save it in a new column. I tried something like the below code:
if(isset($_POST['gamescore'])){
$username=$_SESSION['username'];
$fetch = "SELECT * FROM users WHERE username='$username'";
$fetchid =mysqli_query($db, $fetch);
while ($row=mysqli_fetch_array($fetchid)){
$id = $row['id'];
$username=$row['username'];
$gamescore= $_POST['gamescore'];
$updatescore= "UPDATE users SET score='$gamescore' WHERE id = '$id'";
mysqli_query($db, $updatescore);
$addscore= "SELECT sum(score='$gamescore') AS sum_score FROM users WHERE id='$id'";
mysqli_query($db,$addscore);
$finalscore="UPDATE sum_score SET sum_score = sum(score='$gamescore') WHERE id='$id'";
mysqli_query($db,$finalscore);
}
}
when I run the above code, score column gets updated by the new score, each time the player finishes the game but the sum of the old score and new score is not happening, I would appreciate if someone could help me with this problem.
The database table has columns "username", "id" , "password", "score" and "sum_score".
You can do everything in your code with one query. As has been mentioned in the comments, you should use prepared statements to protect yourself from SQL injection. Try something like this:
if (isset($_POST['gamescore'])) {
$sql = "UPDATE users
SET score = ?,
sum_score = sum_score + ?
WHERE username = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("iis", $_POST['gamescore'], $_POST['gamescore'], $_SESSION['username'])l
$stmt->execute();
}
I am having a little issue getting data from a table with while loop. What i want to do is simple I want to take all data from table cart with cookie value from table orders that matches a cookie value and query tables cart to extract data that matches the cookie value in the cart table and place them in table orders_final . Now this is . Now the final part after querying cart table with cookie value gotten from order table, i now want to place the data into orders_final table with all that matches that cookie value from order and cart
$zomo = $_COOKIE['shopa']; // this is the cookie that is stored in the cart table and updated when the transaction is successful
$get_products = "SELECT * FROM `cart` WHERE cookie_value = '$zomo'";
$limo = mysqli_query($con, $get_products);
while($colo = mysqli_fetch_array($limo)){
$product_id = $colo['product_id'];
$order_quantity = $colo['order_quantity'];
$cookie_value = $colo['cookie_value'];
//var $dance is when i update the table with data after payment and data gotten from my payment processing company
$dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',`reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";
$uii = mysqli_query($con, $dance);
if ($uii){
//this variable insert is where i want to insert all data gotten from cart table above and insert into orders_final, where order table holds the cookie value which was created during shopping which is cookie name shopa held in the variable zomo
$insert = "INSERT INTO `orders_final`(`product_id`, `cookie_value`, `trx_id`, `order_quantities`) VALUES ('$product_id','$zomo','$r_reference','$order_quantity')";
$bena = mysqli_query($con, $insert);
if ($bena){
$delc = "DELETE FROM `cart` WHERE cookie_value = '$zomo'";
$tipee = mysqli_query($con, $delc);
if ($tipee){
perform_success();
}
}
}
}
A better approach is to run fewer queries, that do more. Instead of selecting an entire table and looping over it to run up to 3 queries per iteration (which quickly becomes a lot of queries!), you can use a INSERT INTO...SELECT query instead. Using a transaction, it's also possible to ensure that everything goes through before committing the changes - so you don't end up deleting something that didn't transfer properly.
The code below has been altered to reduce the amount of queries down to three (and none is looped!), and usage of prepared statements has been implemented.
$stmt = $con->prepare("INSERT INTO orders_final (`product_id`, `cookie_value`, `trx_id`, `order_quantities`)
SELECT product_id, ?, order_quantity, ?
FROM cart
WHERE cookie_value=?");
$stmt->bind_param("sss", $zomo, $r_reference, $zomo);
if ($stmt->execute()) {
$stmt->close();
$stmt = $con->prepare("UPDATE orders
SET status=?, time=?, date=?, reference=?, transaction_status=?,
transaction_method=?, final_price=?, order_id=?,
currency=?, referrer=?
WHERE cookie_bought=?");
$stmt->bind_param("sssssssssss", $r_status, $r_time, $r_date, $r_reference, $r_transaction_status, $r_transaction_method, $r_final_price, $r_order_id, $r_currency, $r_referrer, $zomo);
$dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',
`reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";
$stmt = $con->prepare("DELETE FROM cart WHERE cookie_value=?");
$stmt->bind_param("s", $zomo);
$stmt->execute();
$stmt->close();
}
mysqli::prepare()
mysqli_stmt::bind_param()
MySQL INSERT INTO..SELECT
I would like to ask how to display the information based username? I mean when I login, it will lead me to select data page. My select data page has username, name and date. The name is the name of item in spinner, i put these item in spinner. For example, username which is john select item 1 in spinner and it will send to database. Then when go status page, it will only display the item selected by John only in John account. Same as other account, in their account only will display their own item selected.
Below is my select item php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$username = $_POST['username'];
$name = $_POST['name'];
$date = $_POST['date'];
//Creating an sql query
$sql = "INSERT INTO Selection (username, name, date) VALUES
('$username','$name', '$date')";
//Importing our db connection script
require_once('dbConnect.php');
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Selected Successfully';
}else{
echo 'Sorry, You Already Select this item';
}
//Closing the database
mysqli_close($con);
}
?>
View Status Php:
<?php
//Importing Database Script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT * FROM Selection";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_array($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"id"=>$row['id'],
"username"=>$row['username'],
"name"=>$row['name'],
"date"=>$row['date']
)
);
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I am using localhost and phpmyadmin.
Table structure for Selection is below:-
id - primary key Not Null
username NOT NULL,
name NOT NULL,
date NOT NULL,
ALTER TABLE `Selection` ADD UNIQUE `unique_index`(`username`, `name`);
As you haven't mention the Schema of Spinner and Selection table, assuming a simple case for you, the solution would be like instructed below..
When user logs in, capture it's username (usually store it in session till he/she logs out).
In your Status.php your query would be
Select * from Selection where username = '$YOUR_USER_NAME_FROM_SESSION_HERE';
That should be enough as per your requirement.
NOTE: Using variable directly in your query will result in exposure of SQL injection. To prevent Sql injection, refer this answer too.
when the user logged in set the session using $_SESSION["name"] = "$username";
right now session is set then you can access the session variable from anywhere in the view page you retrieve the session using
$user= $_SESSION["name"].
now you fetch the items from the database
like
$sql = "SELECT * FROM Selection where username='$user'";
try it
probably a simple one for you developers out there
I have this code to insert an order_id and order_name into the 'orders' table:
<?php
// start the session handler
require_once('dbfunction.php');
//connect to database
$conn = DB();
require_once('header.php');
//should we process the order?
if (isset($_POST['process'])) {
$order_name = $_POST['order_name'];
//create initial order
$stmt = $conn2->prepare("INSERT INTO orders (order_name) VALUES (?)");
//bind the parameters
$stmt->bind_param('s', $order_name);
// Execute query
$stmt->execute();
I now want to insert the order items into the order_items table and I cant seem to keep that same ID that was created when inserting into the 'orders' table and add it to the 'order_items' table along with the order_items. Here is my code:
//this gets the most recent auto incremented ID from the database - this is the order_id we have just created
$order_id = mysql_insert_id();
//loop over all of our order items and add to the database
foreach ($_SESSION['order'] as $item) {
$prod_id = $item['prod_id'];
$quantity = $item['quantity'];
$prod_type = $item['prod_type'];
$stmt = $conn2->prepare("INSERT INTO order_items (order_id, prod_id, quantity, prod_type) VALUES (?, ?, ?, ?)");
//bind the parameters
$stmt->bind_param('iiis', $order_id, $prod_id, $quantity, $prod_type);
// Execute query
$stmt->execute();
}
echo "<p class='black'>Order Processed</p>";
I would guess it's because whatever database library you are using is doing something to invalidate the mysql_insert_id (assuming it's even using the mysql functions). I'd suggest you look into the library to find out what method they suggest you use instead.
SQL Server has ##IDENTITY
It looks like mySQL has LAST_INSERT_ID();
My guess is you are using mySQL. If not, then please let me know the version so I can update