there is table named Book and this code is supposed to find a specific record and edit it's num to num-1, but it only edit num to -1.
$sql = 'SELECT num FROM Book
WHERE bid="'.$_SESSION["sails bid{$i}"].'"';
if (mysqli_query($conn, $sql)) {
$row = mysqli_fetch_array($query);
$numbers=(int)$row['num']-1;
$sql='UPDATE Book
SET num="'.$numbers.'"
WHERE bid="'.$_SESSION["sails bid{$i}"].'"';
if (mysqli_query($conn, $sql)) {
...
}
}
For one thing, you've overcomplicating this. You don't need to select into PHP, perform the math, and then update. Simple arithmetic can be performed in SQL. For example:
UPDATE Book SET num = num - 1 WHERE bid = ?
Just bind your bid value (preferably using query parameters instead of the string concatenation you're currently using) and you only need to execute that one UPDATE instead of all the code you have now.
Related
This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}
I am very new to PHP. I am trying to run these sqls. The first sql is needed to be runned first in order to get the value needed to be inserted to the two remaining sqls.
Here is what I done:
$sql = "SELECT (unitPrice) FROM product WHERE productID = '".$pid."'";
$sql1 = "INSERT INTO order (orderID) VALUES ('".$rnd_id."');";
$sql1 .= "INSERT INTO order_details (orderID,orderType,orderDate,orderTime,quantity,orderPrice,discount,discountPrice,employeeID) VALUES ('".$rnd_id."','".$type."','".$date."','".$time."','".$quantity."','".$oprice."','".$dis."','".$dprice."','".$eid."')";
if($result = mysqli_query($link, $sql)){
while($row = mysqli_fetch_array($result)){
$price = $row['unitPrice'];
$oprice = (double)$price * (double)$quantity;
}
} else{
echo "Something went wrong. Please try again later.";
}
$dprice = $oprice - $oprice * $dis;
//Free result set
mysqli_free_result($result);
if(mysqli_multi_query($link, $sql1)){
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
//Records created successfully. Redirect to landing page
header("location: index5.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
First of all: you really should use prepared statements. It is not only a lot safer, but also makes your life easier as you can write far cleaner code.
Read this on the why and this page on the how. In the example below I'm using PDO.
The first thing wrong with your code: you use variables before they are defined. Look at
$sql1 .= [...] VALUES
('".$rnd_id."','".$type."','".$date."','".$time."','".$quantity."',
'".$oprice."','".$dis."','".$dprice."','".$eid."')";
$oprice and $dprice are used, but they are defined only later in your code. So they don't have a value on the moment you construct the query.
Second: take a look at the reserved words in mysql.
ORDER is a reserved word, you shouldn't use it for a table name.
Then, you use a seperate SELECT query to get the price and then use it in the INSERt query. It is not necessary. Databases are quite good at combining tables. So you can use a SELECT with your INSERT, combining the price from product with the INSERT in order_details
I suppose the variables $rnd_id, $type, $quantity, $dis are defined somewhere else, as that's not shown in your code.
Using a prepared statement, inserting $rnd_id can be written like this:
//construct a query with :rnd_id as a parameter
$query= 'INSERT INTO order_id (orderID) VALUES (:rnd_id)';
//bind the variable to the parameter
$bind=[
':rnd_id'=>$rnd_id
];
//prepare the statement
$statement = $link->prepare($query);
//execute the statement
$statement->execute($bind);
The second INSERT uses a SELECT to get the product price from the product table. As you can see, I let mysql do the calculations in the query, so no need to do it in seperate code.
Instead of using $date and $time I simply tell mysql to use the current date and time with NOW()
Why I use multiple parameters for quantity and discount: sadly PDO can't re-use a parameter. So if you want to use it again in the query, you have to define it again.
$query = '
INSERT INTO order_details (
orderID,
orderType,
orderDate,
orderTime,
quantity,
orderPrice,
discount,
discountPrice,
employeeID
)
SELECT
:rnd_id ,
:type ,
NOW() ,
NOW() ,
:quant1 ,
(unitPrice * :quant2), //'unitPrice from table product, mysql does the calculation'
:disc1 ,
(unitPrice * :quant3) - ((unitPrice * :quant4) * :disc2) ,
:empID
FROM product WHERE productID = :prodID
';
$bind=[
':rnd_id' =>$rnd_id,
':type' =>$type,
':quant1' =>$quantity,
':quant2' =>$quantity,
':quant3' =>$quantity,
':quant4' =>$quantity,
':disc1' =>$dis,
':disc2' =>$dis,
':prodID' =>$pid,
':empID' =>$eid
];
$statement = $link->prepare($query);
$statement->execute($bind);
There's a lot more say about your code, but this covers the basics. I've tested the queries (they work), but not the PHP code. So there could be an error in there somewhere.
I have a query like:
SELECT id, name, surname, fromId, toId, msg_text, readed FROM messages WHERE toId = 2;
So I want to update all selected rows.readed = 1. And Query must return all selected rows.
These action must do in one query if possibe.
Sorry for my english
Short answer: No, it is not possible in a single query.
A little less short answer: There is something known as a command-query separation which in short suggests that a command should do something and return nothing and a query should do nothing and return something. I recommend following this principle if you intend on building good software.
I wont get into why this is not possible because I myself am not that much of an SQL guru and I could only guess but I would suggest an easy solution to your problem.
When you get your results then you are most likely processing them in PHP. Assuming the results are sorted in ascending order - on the first iteration grab the minimum id and on the last one grab the maximum id, then run an update query:
UPDATE messages SET readed = 1 WHERE toId = ? AND (id >= <minimum id> AND id <= <maximum id>)
On a side note - name and surname are probably not what you want to store in a messages table.
You can update only with an UPDATE query. An UPDATE query can return only one thing: that is number of affected rows. So, you cannot update and select the value you need in a single query.
Have a look here Update a table then return updated rows in mySQL
You can do that with stored procedure.
Create a stored procedure which executes the update and the select as well.
Eg:
DROP PROCEDURE IF EXISTS myproc;
delimiter //
CREATE PROCEDURE myproc()
begin
set #qry='select id, name, surname, fromId, toId, msg_text, readed from messages where toId = 2';
prepare query from #qry;
execute query;
update messages set readed=1 where toId = 2;
end //
Then you can run the query through this procedure.
Eg:
$sql = "call myproc()";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
I check if the the url is present first and see if he is up voting first time, if so then i will add the users repute to the upvoted column, but i want to add only to that url not to all urls, this code is adding to all all tuples in "upvotes" column, i want it to add only to a particular tuple.
<!Doctype html>
<html>
<?php
$c=$_GET['a'];// users name
$d=$_GET['b'];// usesrs id
$e=$_GET['c'];// users repute
$ur=$_POST['url'];
// Create connection
$con=mysqli_connect("localhost","root","","repute system");
if(mysqli_connect_errno()){
echo "ERROR ".mysqli_connect_error();
}
$sql = mysqli_query($con,"SELECT * FROM sites");
if (mysqli_num_rows($sql) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($sql))
{
if($ur == $row['URL'] && $d != $row['id'])
{
$ne = $row['upvotes'] + $e;
$sol = mysqli_query($con, "UPDATE sites SET upvotes = $ne ");
$bew = mysqli_query($con,"INSERT INTO v_sites(teacher_id,URL,vote) VALUES ('$d','$ur','$e')");
echo "Upvoted the site ";
echo $ur;
}
}
} else {
echo "Sorry before upvoting you have to block it first or you are trying to upvote your own report, in which you cant";
}
?>
</html>
You need a WHERE clause that matches the URL:
$stmt = mysqli_prepare($con, "UPDATE sites
SET upvotes = upvotes + 1
WHERE url = ? AND id = ?";
mysqli_stmt_bind_param($stmt, "ss", $ur, $d);
mysqli_stmt_execute($stmt);
You don't need the SELECT or while loop, since MySQL can find the matching rows and update them all by itself.
You also shouldn't have the INSERT query inside the loop, since it's inserting the same row each time.
And you should switch to prepared statements, as shown above, instead of inserting strings into your queries, since your code is subject to SQL injection.
All your rows are being updated because you are not using a where clause.
UPDATE sites SET upvotes = $ne
should be changed to:
UPDATE sites SET upvotes = $ne WHERE id='$d'
However, if $ne is also a string, $ne should also be quoted:
UPDATE sites SET upvotes = '$ne' WHERE id='$d'
Read up on UPDATE:
https://dev.mysql.com/doc/refman/5.0/en/update.html
"My table's name in sites it has 5 columns, which are URL,status,upvotes,downvotes, id and all are varchar with 30 length"
This tells me that id is VARCHAR also; not a good idea but that's up to you. It's best to use int for queries like this should all your id's be numerically-based.
Which is why using quotes WHERE id='$d' around the $d variable will be required.
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Say I have this loop:
foreach ($array as $a) {
if ($a == $b) {
mysql_query("UPDATE table SET this = 'that' WHERE id='$a'");
}
}
And a table...
id this blah
------------------------
1 that 54
2 that 73
3 there 27
Inside that loop, I also want to find the value stored in the tables blah field from the current record that is being updated.
Whats the most effective way to do this?
You can have your query consist of multiple statements, and the last statement is what is used for the "results".
So, you can just add a "select" statement to the end of the update query and treat it like a normal select statement:
UPDATE table SET this = 'that' WHERE id='$a'; SELECT blah from [your table] WHERE id = '$a'
The advantage with this method is that it doesn't require an additional DB call.
Of course, you will want to be escaping the values put into the SQL statements to prevent SQL injection, but that's another matter.
Update
This was my first second SO answer which I felt needed revising. Searching around, I found a much better answer to your question.
From the accepted answer for question: SQL: Update a row and returning a column value with 1 query
You want the OUTPUT clause
UPDATE Items SET Clicks = Clicks + 1
OUTPUT INSERTED.Name
WHERE Id = #Id
Similar question: Is there a way to SELECT and UPDATE rows at the same time?
Old Answer
Add a SELECT statement to the end of your UPDATE query.
mysql_query("UPDATE table SET this = 'that' WHERE id='$a'; SELECT blah WHERE id='$a';");
This prevents you from ensuring the update took place since mysql_query only returns the last statement's result.
You could also write a custom function that performs both statements but, for instance, won't preform the SELECT if the UPDATE failed, etc.
** Skeleton Function - Not Tested **
function MyUpdate($query, $id){
$retVal = "-1" // some default value
$uResult = mysql_query("UPDATE table SET this = 'that' WHERE id='$a'");
if( $uResult )
$result= mysql_query('SELECT blah WHERE id=$a');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$retVal = $result;
}
return $retVal;
}