echo updated values instead of old values - php

How do I echo the latest values in column1? The below code echos the values before the update.
while($line = mysql_fetch_array($result)) {
$Student = $line["calss8"];
$querySf = "SELECT SUM(ABC) AS val1 FROM tbl1 WHERE student = '$Student'";
$resultSf = mysql_query($querySf);
$rSf = mysql_fetch_array($resultSf);
$totalSf = $rSf['val1'];
$totTMonth = $totalSf;
mysql_query("UPDATE tbl4 SET column1 = $totTMonth WHERE student = '$Student' LIMIT 1");
}
echo $line["column1"].",,";

As far as I know, you'll have to make a separate query to see what was just updated. I mean, run your select, perform your update, then do another select. You can get general information like how many rows were updated, but I don't think you can get specific information like the changed values in a column. Phil was right in suggesting that you should just print out the '$totTMonth' value since that is what you are updating your column with. That would be less overhead than doing another query to the database.

I think that problem starts before the code above. This code line will display the select results :echo $line["column1"].",,";. The variable $line is set before the code above. My solution is to do the following:
$result1 = mysql_query("SELECT column1 FROM student ..."); /* I insert the select query here */
While($row= mysql_fetch_array($result)) {
echo $row['column1'].",,";
}

Related

nested while loop stops after first iteration PHP

I'm fairly new to this so I am probably missing something very basic, but I am trying to write some PHP script. I want to normalize my main table of data, which is info on used cars, make, model, price, etc. So I have another table with all of the unique car manufacturers in, this stores the makeName with a unique id makeId In my script, I connect to the database, read in all of the data from the main table, run it as an SQL query, then store it as a variable. I do the same with the make table.
Then I try to run through a nested while loop to replace all of the strings in the main table in the Manufacturer column with the makeId from the make table so that I can link these two tables. It works for one iteration then stops, I've tried adding !==FALSE after the fetch_assoc in either and both while loops, but that gives me infinite loops I think. Here is my code...
<?php
include("conn.php");
$sqlAll= "SELECT * FROM carData";
$carDataResult = $conn->query($sqlAll);
if(!$carDataResult){
echo $conn->error;
die();
}
$sqlMake = "SELECT * FROM 000make";
$makeResult = $conn->query($sqlMake);
if(!$makeResult){
echo $conn->error;
die();
}
while ( $make =$makeResult-> fetch_assoc()){
$makeID = $make['makeId'];
$makeName = $make['makeName'];
while ($row = $carDataResult->fetch_assoc()){
$sqlUpdate="UPDATE carData SET Manufacturer = '$makeID'
WHERE Manufacturer='$makeName' AND Manufacturer IS NOT NULL";
$res = $conn->query($sqlUpdate);
if(!$res){
echo $conn->error;
die();
}
}
}
?>
About 10 mins after I posted the question, after staring at this all day, I realised that I didn't need a nested loop at all and wrote the code below, which is clunky but it solved the problem, but I like your solution better #TangentiallyPerpendicular...thanks for your help guys...
while ($make =$makeResult-> fetch_assoc()){
$makeID = $make['makeId'];
$makeName = $make['makeName'];
$sqlUpdate="UPDATE carData SET Manufacturer = '$makeID'
WHERE Manufacturer='$makeName' AND Manufacturer IS NOT NULL";
$res = $conn->query($sqlUpdate);
if(!$res){
echo $conn->error;
die();
}
}
As a general rule, reading a result set and looping through it to run successive queries is the wrong way to deal with this sort of problem. You can do it all in a single query:
update carData set `Manufacturer` = (select `makeId` from `000make` where 000make.makeName=carData.Manufacturer)
Your entire program becomes:
<?php
include("conn.php");
$sqlAll= "update carData set `Manufacturer` = (select `makeId` from `000make` where 000make.makeName=models.Manufacturer) ";
$carDataResult = $conn->query($sqlAll);
if(!$carDataResult){
echo $conn->error;
die();
} else {
echo "Update Successful"
}
As an aside, I'd create a new column (called, perhaps, makeId) in your carData table and insert the data there rather than overwriting the Manufacturer column. That way you retain the Manufacturer column if something goes wrong. You can drop that column later.

How to store a PHP variable from a SQL table INT camp

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);
}
}

Best way to identify a mysql changed "group by" field value in a statement fetch in php?

I have a sql query in my php:
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
Now, I have to echo back several HTML tables based on different orderIds, so basically if the orderId is changed, a new HTML table will be created and contains the info of all the things under this orderId. This is what I have done(kinda pseudocode, please ignore the syntax error. My real code is far more complicated but the idea is here: set an oldOrderId and check it with the newly fetched orderId and see if the orderId is changed):
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
for ($i = 0; $i<$count + 1; $i++ ){
if ($row = $stmt->fetch()){
$orderId = $row["orderId"];
$2ndField = $row["2ndField"];
$3rdField = $row["3rdField"];
...
// check if $oldOrderId is set
if (isset($oldOrderId)){
// and compare, if the orderId changes, end the table and create a new one
if ($oldOrderId != $orderId){
echo "</table><br>";
echo "<table><tr><th>...</th></tr>";
...
//UPDATE old orderId
$oldOrderId = $orderId;
// if orderId doesn't change, continue echo table content
} else {
echo "<table><tr><td>...</td></tr>";
}
// if the oldOrderId is not set, it means this is the first fetched row, and the very first table will be created
} else {
echo "<table><tr><th>...</th></tr>";
...
echo "<table><tr><td>...</td></tr>";
...
//SET oldOrderId
$oldOrderId = $orderId;
}
}
if ($i == $count) {
//End the last table
echo "</table><br>";
}
}
The code can run but will be buggy sometimes and I don't think this is a smart way to identify it. Is there any existed method like
$row = $stmt->fetch().prev()
to get the last row's orderId's value? Or if there's any better way to perform it?
Thanks!
The problem is your inclusion of GROUP BY orderId in your query. What this does is give you one row per each orderId in your table.
Since you are using SELECT *, then all you are getting back is one row for each orderId and one of the other values in the table for each of the other fields.
When using GROUP BY, you usually want to add a "group function" - like SUM(), COUNT(), GROUP_CONCAT(), etc. - to your query.
Your approach with the $oldOrderId is fine and could work if you change your query to something like:
SELECT * FROM orderTaken
WHERE orderStatus='10'
ORDER BY orderID DESC, orderTakenTime DESC

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Get the last checked checkboxes

I'm not sure how to accomplish this issue which has been confusing me for a few days. I have a form that updates a user record in MySQL when a checkbox is checked. Now, this is how my form does this:
if (isset($_POST['Update'])) {
$paymentr = $_POST['paymentr']; //put checkboxes array into variable
$paymentr2 = implode(', ', $paymentr); //implode array for mysql
$query = "UPDATE transactions SET paymentreceived=NULL";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentdate='0000-00-00'";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentreceived='Yes' WHERE id IN ($paymentr2)";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentdate=NOW() WHERE id IN ($paymentr2)";
$result = mysql_query($query);
foreach ($paymentr as $v) { //should collect last updated records and put them into variable for emailing.
$query = "SELECT id, refid, affid FROM transactions WHERE id = '$v'";
$result = mysql_query($query) or die("Query Failed: ".mysql_errno()." - ".mysql_error()."<BR>\n$query<BR>\n");
$trans = mysql_fetch_array($result, MYSQL_ASSOC);
$transactions .= '<br>User ID:'.$trans['id'].' -- '.$trans['refid'].' -- '.$trans['affid'].'<br>';
}
}
Unfortunately, it then updates ALL the user records with the latest date which is not what I want it to do. The alternative I thought of was, via Javascript, giving the checkbox a value that would be dynamically updated when the user selected it. Then, only THOSE checkboxes would be put into the array. Is this possible? Is there a better solution? I'm not even sure I could wrap my brain around how to do that WITH Javascript. Does the answer perhaps lie in how my mysql code is written?
--
Edit: Ok, just more information. The SQL Queries I have going on - the first two are to wipe everything clean (in case a checkbox is UNCHECKED) and then next they are updating the SQL queries based on which checkboxes are checked upon post.
However, I'm thinking this is a bad way to do it. Why force the database to first wipe out ALL data for paymetreceived, paymetdate? The problem with this, also, is that *all the subsequent checkboxes, regardless of how long ago they were checked, get updated in the SQL query as it is now.*There's got to be a way to update it better. I'm just not sure HOW to do it. any ideas?
You are not filtering by id in this queries:
$query = "UPDATE transactions SET paymentreceived=NULL";
$query = "UPDATE transactions SET paymentdate='0000-00-00'";
Try adding: WHERE id IN ($paymentr2)";
The problem is in your first 2 sql UPDATE statements. You don't provide a WHERE clause, so that's going to update all your records. You could add:
WHERE id IN ($paymentr2)
to your first two UPDATE statements

Categories