Updating value to database using PHP - php

I have some problem when want to update my value in database. There is no error shown. The page will ust redirect as indicated even when the value is not updated.
This is the code for user to input..
echo "<td bgcolor='#FFFFFF'><input id='id' name='pro_id[]' type='text'></td>";
echo "<td bgcolor='#FFFFFF'><input id='name' name='pro_name[]' type='text'></td>";
echo "<td bgcolor=‘#FFFFFF’><input id='quan' name='pro_quan[]' type='text'></td>";
Below is the code for my insert value..
$query = "INSERT INTO product (username, pro_id, pro_name, pro_quan) VALUES ";
for ($i = 0; $i < count($_POST['pro_id']); $i++) {
$query .= " ('{$username}', '{$id[$i]}', '{$name[$i]}', '{$quan[$i]}'),";
}
$query = substr($query, 0, -1);
$result = mysqli_query($con, $query) or die(mysqli_error($con));
The insert code work fine. The value is inserted into the database.Below is my update code..
$sql = "SELECT * FROM product where username = '$username'";
foreach($_SESSION['product'] as $item)
{
$id = $item['pro_id'];
$name = $item['pro_name'];
$quan = $item['pro_quan'];
$sold = $item['pro_sold'];
$sql="UPDATE product SET pro_id='".$id."', pro_name='".$name."', pro_quan='".$quan."', pro_sold='".$sold."' WHERE username = '".$username."'";
}
$results=mysqli_query($con, $sql);
The value couldn't be updated. I have no idea what have gone wrong.So, any help will be appreciated.Thanks

$id and $quan in your update query are between single quotes. I don't know anything about your database structure, but something tells me those values are numbers and not strings. Here is the updated line:
$sql="UPDATE product SET pro_id=".$id.", pro_name='".$name."', pro_quan=".$quan.", pro_sold='".$sold."'";
You might have to remove the quotes around $sold as well.

Need to put sql execution in foreac, as below...
$sql = "SELECT * FROM product where username = '$username'";
$results=mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($results)){
$id = $row['pro_id'];
$name = $row['pro_name'];
$quan = $row['pro_quan'];
$sold = $row['pro_sold'];
$sql="UPDATE product SET pro_id='".$id."', pro_name='".$name."', pro_quan='".$quan."', pro_sold='".$sold."' WHERE pro_id = '".$id."' ";
mysqli_query($con, $sql);
}

first of all check the pro_id that is primary key or not.
if it is a primary key than write query in this way.
$sql="UPDATE product SET pro_name='".$name."', pro_quan='".$quan."', pro_sold='".$sold."' WHERE pro_id = '".$id."' ";
because primary key generate error if the uniqueness of the column is disturb.

Thanks guys for all your helping. I have change my update code by using for loop.
Below is the solution..
for ($i = 0; $i < count($_POST['pro_id']); $i++) {
$sql="UPDATE product SET pro_name='".$name[$i]."', pro_quan=".$quan[$i].", pro_sold=".$sold[$i]." WHERE pro_id=".$id[$i]."";
$results=mysqli_query($con, $sql);
}

Related

Update one value at multiple ID's in database table

$upload_files=implode(' ',$_GET['upload_files']);
$upload_user=",".$_GET['upload_user'];
echo $upload_files;
$sql = "UPDATE {$db_pr}files SET userID = CONCAT(userID,'".$upload_user."') WHERE id IN ('".$upload_files."')";
IN takes a comma-delimited string I believe.
try:
$upload_files=implode("','",$_GET['upload_files']);
Well, I got the solution. I used for loop to achieve the result.
$upload_files=$_GET['upload_files'];
$upload_user=",".$_GET['upload_user'];
for ($i = 0, $count = count($upload_files); $i <= $count; $i++) {
$sql = "UPDATE {$db_pr}files SET userID = CONCAT(userID,'".$upload_user."') WHERE id = '".$upload_files[$i]."'";
$result = mysqli_query($mysqli,$sql) or die("Error occurred - tried to update file.");
}
echo "<div class='loginMessage loginSuccess'>Assigned Successfully!!!</div>";

MYSQL query using a set of values (values stored from a session array) not working

I'm just a beginner and I'm doing a project (a shopping cart). User can add a product to the cart and the id of the product stores in a session. When I use those ids to echo out PRICE from DB it's not working. I'm using PHP & MYSQL. Here is my code
if(count($_SESSION['cart_items'])>0){
// getting the product ids
$nos = "";
foreach($_SESSION['cart_items'] as $no=>$value){
$nos = $nos . $no . ",";
}
// removing the last comma
$nos = rtrim($nos, ',');
//echo $nos; (will display like this INT VALUES 1,2,3,4)
$nos=mysql_real_escape_string($nos);
$site4->DBlogin();
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
$result = mysql_query($qry);
$row = mysql_fetch_assoc($result);
echo $row['price'];
}
PHP is not recursively embeddable:
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
^---start of string end of string ---^
Since you're already in a string, .implode(...) is just plain text, NOT executable code.
This means your query is illegal/invalid SQL, and if you had even basic/minimal error checking, would have been told about this:
$result = mysql_query($qry) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
I have fixed the issue and thanx MARC for your suggestions.
I was making two mistakes:- IMPLODE input field was not an array. and as Marc said the query was not executable.
Changes made :-
$nos = rtrim($nos, ',');
**$narray = array($nos);**
$fgmembersite4->DBlogin();
$qry = **'SELECT * FROM vendorproducts WHERE product_no IN ('.implode(',',$narray).')'**;
$result = mysql_query($qry) or die(mysql_error());
**while (**$row = mysql_fetch_assoc($result)){
echo $row['price'];}

mysql insert statement inside a while statement adds only 1 record

I have this code (refer below)
$sql = "SELECT * FROM records";
$result = mysqli_query($this->db,$sql);
while($row = mysqli_fetch_assoc($result)){
$itemid = $row['id'];
$itemname = $row['itemname'];
$itemdesc = $row['itemdesc'];
$brand = $row['brand'];
$serialno = $row['serialno'];
$nostock = $row['nostock'];
$price = $row['price'];
$onsale = $row['onsale'];
$poster = $row['poster'];
$thedate = $row['thedate'];
$sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
$result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
return $result;
}
as you can see from the above codes, it will first pull all the data from db table named "records" and then put each row into there corresponding variable and then insert the stored data (those data that has been pulled from db table name "records" and stored on there corresponding variable) to db table named "backupp". Now, the problem is, it only add one record to backup (the record that has been pulled first) which supposedly it should add all the pulled record from db table named records to db table named backup. why?? any suggestions, recommendations, clues and ideas would be greatly appreciated. Thank you!
PS: its like export and import to other table with same structure but I have my own reason why I want to do it this way and assume I already successfully connected to a database ($this->db) called "inventory" and there is db table name there such as "records" and "backupp" with same structure.
And you can easily backup same table this way: INSERT INTO backupp SELECT * FROM records
You have a return statement inside the while loop causing it to exit after one iteration.
Remove the return $result; line and it should work.
change your code into this (see below).
$sql = "SELECT * FROM records";
$result = mysqli_query($this->db,$sql);
$x = 0;
while($row = mysqli_fetch_assoc($result)){
$itemid = $row['id'];
$itemname = $row['itemname'];
$itemdesc = $row['itemdesc'];
$brand = $row['brand'];
$serialno = $row['serialno'];
$nostock = $row['nostock'];
$price = $row['price'];
$onsale = $row['onsale'];
$poster = $row['poster'];
$thedate = $row['thedate'];
$sql = "INSERT INTO backupp SET id='$itemid', itemname='$itemname', itemdesc='$itemdesc', brand='$brand', serialno='$serialno', nostock='$nostock', price='$price', onsale='$onsale', poster='$poster', thedate='$thedate'";
$result = mysqli_query($this->db,$sql) or die(mysqli_error($this->db));
$x++;
}

passing php variable in mysql update

I am trying to pass global variable in $_post in following way..
Unable to get through..Please help
<?php
include '/home/mechdipl/db.inc';
echo $_GET['lec'];
$lect=$_GET['lec'];
$atnds=$_GET['atnds'];
$size = count($_POST['id']);
$i = 0;
while ($i < $size) {
$name = $_POST['name'][$i];
$lectr = $_POST[$lect][$i];
$atndsr = $_POST[$atnds][$i];
$id = $_POST['id'][$i];
$query = "UPDATE stud SET name='$name', $lect ='$lectr',$atnds ='$atndsr' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$name<br /><br /><em>Presenty Updated!</em><br /><br />";
++$i;
}
?>
You have errors in your query, use this
UPDATE stud SET name='$name', lect ='$lectr', atnds ='$atndsr'
WHERE id = '$id' LIMIT 1
and you just wrote the query, not performing it, for that you have to use mysqli_query() or mysql_query() function....please let me know if you have any more doubts. and even in your $_POST global variable you have used
$lectr = $_POST[$lect][$i]; $atndsr = $_POST[$atnds][$i];
I know that it is not correct way. So, please before querying print out $_POST global variable and then use those keys in above. It could be like this
$lectr = $_POST['lect'][$i];
$atndsr = $_POST['atnds'][$i];

While loop not printing all answers

This might be really simple, but i cannot figure out the problem with this code:
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2. However the reached is echoed only once. Does anyone see a potential problem with the code?
P.S: My bad, $sql is being repeated, that was a silly mistake
It will only echo once because of this line :
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
your overwriting the $sql variable.
Why not just run a single query and join the data you require ?
try ($sql2 instead of $sql and $sql[0] to $sql2[0]):
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
I think it'll be because you are ressetting the sql variable
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
when you are still using it in the while loop. :P
It's probably this line:
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
Try using a different variable name.
You are changing the $sql variable inside the loop, therefore the next time you run $row = mysql_fetch_array($sql), the value will be different (probably won't be any based on your code).
Inside the while loop you are re-using the same variable: $sql. This is used to control the terminating condition of the loop.
Using a different variable name, e.g. $sql2 should leave the original variable intact and the loop should proceed as expected.

Categories