Mysql php Update doesnt work in while loop - php

I am new in programming and I came across issue with Mysql Update code. I have 4 different row values in '100m' Column and I am trying to use While loop to calculate $points1 for each different value of row, then afther calculatin, update table with it depending on row value. But from all 4 row just 3rd one gets Total_score update.
Table:
Table Structure:
Code:
<?php
include ("config.php");
$sql= "SELECT * FROM data_from_file";
$result= $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$P=$row['100m'];
$A=25.4347;
$B=18;
$C=1.81;
$points1 = $A*(($B-$P)**$C);
$insert =$db->query("UPDATE data_from_file SET Total_score=$points1 WHERE 100m=$P");
echo $P;
echo "<br>";
echo $points1;
echo "<br>";
};
}
?>
Why just 3rd one is updating?

You shouldn't use names that begin with numbers on your table columns.
$insert =$db->query("UPDATE data_from_file SET Total_score=$points1 WHERE `100m`=$P");

Try this
Use single quotes for variables
$insert =$db->query("UPDATE `data_from_file` SET `Total_score`='$points1' WHERE `100m`='$P'");

Using WHERE 100m=$P is bad idea, because it updates all rows where value of 100m equals $P. You should use WHERE id=$row['id'], so you will be sure that only one row will be updated.
Can you post a table structure? I want to know columns types.

Related

PHP function doesn't increment int as it should

On my XAMPP server I have a database table on phpMyAdmin. In that table, I have a few columns, and one of them is id column (Integer).
I want to get the latest added item's ID, increment it by one and then assign it to a new item that the function adds to the table.
The problem is that whenever there is a new item, it is automatically assigned with 1 as id, nothing above 1.
$sql = "SELECT * FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
if( $_SESSION["increment"] == "yes"){
$_SESSION["id"] = $row["id"];
}else
$_SESSION["id"]=$_SESSION["id"]+1;
}
} else {
$_SESSION["id"] = 1;
}
This will give you last increment Id.
$sql = "SELECT id FROM items order by id DESC LIMIT 0,1";
Then you dont want have a while loop to find last increment Id.
error reporting said what? and mysqli_error($conn)?
-- Fred-ii-
The above request by Fred -ii- sums it up, if your ->num_rows is returning zero or not a number (false) then you have an SQL error, so you need to check your error logs, and check your database connection.
Have you started your session with session_start?
Do you intend that the first else calls without brackets, only executing the single following line, $_SESSION["id"]=$_SESSION["id"]+1; ?
It seems to me that you need well known AUTO_INCREMENT functionality built inside MySQL database. Just define in your database schema for your table that column is AUTO_INCREMENT column type, and it will be automatically incremented by 1 upon each new insert into table.

echo updated values instead of old values

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'].",,";
}

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Why is this PHP-MySQL code not working properly?

It was working before and maybe someone made changes to the code and I cant detect the problem after much debugging so hopefully someone can help.
I have an html form that lets a user choose a set of option and then on form submit, POSTS these options in an array which works perfectly fine. Then I am writing the elements of an array to a MySQL table and this is where the problem occurs. My code was working fine before but now its all weird. The outputs mix up for some reason.
Below is the array values passed and then the output below the arrays.
Here is my code that writes the array values to MySQL:
error_reporting(-1);
$arr=$_POST["itemsToAdd"];
$cal=$_POST["calendar"];
print_r($arr);
// Make a MySQL Connection
//empty table first to remove any previous old on-calls stored.
$query = "truncate table ProdOnCallSetup";
if(mysql_query($query)){
}
else{
}
foreach ($arr as &$value) {
// Insert a row of information into the table "ProdOnCallSetup"
mysql_query("INSERT INTO ProdOnCallSetup
(Email) VALUES('$value') ")
or die(mysql_error());
}
Here is the code giving the output or displaying the rows in MySQL:
<ol class=”list_style”>
<?php
//make MySQL connection
$query = "SELECT * FROM ProdOnCallSetup";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<li>".$row['Email']."</li>";
echo "<br />";
}
?>
</ol>
See the problem here? Even though I write them in the correct order in MySQL when I display them the order mixes up. Order is Justin, Achau, Chellatamby but when I echo is out from the DB its Achau, Chellatamby, Justin
Unless you specifically use an ORDER BY clause in your SELECT statement, the order in which rows are returned is indeterminate and may change.... it doesn't matter what order you added the records in, this is irrelevant... use ORDER BY...
SELECT * FROM ProdOnCallSetup ORDER BY Email
(or whatever column id you want to order them on)
If you want to order them in the order you added them to the database, you'll need an autoincrement column on the table, and order by that column

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)

Categories