Why is this PHP-MySQL code not working properly? - php

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

Related

PHP fetch MAX values from MySQL table for each different user

I have a table with many different users on my website. They upload the picture. How can I display the last uploaded picture with the highest ID number?
If I do this query:
SELECT user_name, MAX(pictid) FROM `pictures` GROUP BY user_name;
It works in PHP My Admin, but it returns empty result on the website.
Username is written correctly, just ID part is empty. Why is that? That is my code:
include('connection.php');
$sql = "SELECT user_name, MAX(pictid) FROM `pictures` GROUP BY user_name;";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["user_name"] . "</td><td>". $row["pictid"] . "</td><td><img style='width:90px;' src='../uploads/".$row["picture"]."'</td><tr>";
}
}
When using functions like MAX(), SUM(), COUNT() etc, MySQL will return those values with a different name (so it won't collide with other column names you have in the query).
So in your case, instead of $row["pictid"], it should be $row["MAX(pictid)"].
However, since you're not selecting the pictid "as is", you can alias that function:
SELECT user_name, MAX(pictid) as pictid FROM `pictures` GROUP BY user_name
(note the as pictid in the query above)
Now you can fetch the value using:
$row['pictid']
Side note:
I would recommend that you display all errors and warnings while developing in your local environment. In this case, you should have gotten a warning about undefined index/array key pictid, which would have helped you debugging the problem.
And don't forget the fix the broken <img> tag as #brombeer pointed out in the comments to your question.

Mysql php Update doesnt work in while loop

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.

Comparing a PHP variable to values in MySQL column

Just a little assistance, This is a pretty simple problem but it doesn't seem to work right. I am just comparing the value in a variable with all the values in a sql column. Same as if I were to compare a username input to the list of usernames in a sql column. This however is just to compare that the item id being stored in the column for that row is not an item id that is already in use.
I tested the value that I am getting back from the sql query and it is equal to the item id I typed in the input. What you will see below is the actual test to see if the id I am getting back is the one that I am looking for as well as the id of the row I can find that value in. The results I get is
2, 000002 (which is correct) that is what I am looking for.
$itemId = $_POST['itemId'];
if($sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'")){
while($data = $sqlItemId->fetch_assoc()){
printf("<p>%s, %s</p>", $data['id'], $data['itemId']);
die();
}
Then I took this out and tried to compare the value in the variable which is the same itemId already stored (000002). that is where I am going wrong.
I modified the code to look like this for further testing. Seems straight forward yet i am getting a FALSE response providing the latter echo statement "Item Id is not in use" But it is in the DB. I tried it a few different ways based on what I read in stackoverflow but none are giving me the right answer.
$sqlItemId = $dbCon->query("SELECT * FROM CVCinStoreCoins WHERE itemId = '$itemId'");
if($itemId == $sqlItemId){
echo "This item id is already in use. \n";
die();
} else {
echo "Item Id is not in use:";
die();
}
At one point I even tried a while statement to fetch the associated values prior to testing it but that didn't turn up a positive result either. Any suggestions?
Inside $sqlItemId you have the full table row (if any), not only its ID; change the SQL into a count and check the number of rows returned (if greater than 0 you have a duplicate):
$rowsCount = $dbCon->query("
SELECT COUNT(*)
FROM CVCinStoreCoins
WHERE itemId = '$itemId'
");
I don't know what $dbCon is (Doctrine DBAL? mysqli?) so I can't tell you how to use query's result.
Wy don't you just count it,
$result = $dbCon->query("SELECT COUNT(itemId) FROM CVCinStoreCoins WHERE itemId = $itemId");
if $result > 0

Using Tables in PHP

I'm sorry if this question frustrates anyone ... I am truly a beginner to PHP + MYSQL but I would love to make some progress on this one!
My Goal:
To create a table that I can view in a web page.
To be able to add data (rows) to this table and still have the data be there the next time the page is loaded.
Step 1: Creating the table
<html>
<body>
<?php
// Conect to MYSQL
$con = mysql_connect("localhost", "My_Username", "My_Password") or die(mysql_error());
echo "Connected to MYSQL </br>";
mysql_select_db("My_Database") or die(mysql_error());
echo "Connected to Database";
// Create a MySQL table in the selected database (called ExampleTable)
$sql = "CREATE TABLE ExampleTable
(
// Set the primary key (personID)
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
ColumnOne varchar(15)
ColumnTwo varchar(15)
ColumnThree varChar(30)
)";
// Execute query
mysql_query($sql,$con);
mysql_query("INSERT INTO ExampleTable(ColumnOne, ColumnTwo, ColumnThree)
VALUES ('Data1', 'Data2', 'Data3')");
mysql_query("INSERT INTO ExampleTable(ColumnOne, ColumnTwo, ColumnThree)
VALUES ('Data_Data1', 'Data_Data2', 'Data_Data3')");
mysql_close($con);
?>
</body>
</html>
So, I have now created a MYSQL table with two three columns, and two rows of data. How can I get this table to show up on a web page?
Step 2: Saving / Retrieving saved data
Is there some way that I can add data to a table, so that the data will be there permanently? - or is this how it works by default?
For example: Let's say that I have a form with a button on it. When the button is clicked a new row is added to the table 'ExampleTable'. The next time the user visits the page the table will be updated with his newly added data.
Thank you very much for any help. I understand that I am a beginner and do not fully understand these topics yet. Any responses will be greatly appreciated.
I'd recommend creating the table in a separate step, not from PHP; you don't want every time your web page is refreshed to create a new table.
Once your table is created, you can get the data from it by executing (within your PHP, using mysql_query) a query like "SELECT * from {tablename}". Once you've got that query result from mysql, then you can use the various PHP looping and mysql record reading methods to output the results from your query in the form you want into the page your PHP script will be serving to your client.
There are SELECT and UPDATE queries to do this. For example if you want to show data in a table, you would use query looking like this:
SELECT * FROM ExampleTable
In PHP, you can work with these data for example like this:
$query = mysql_query("SELECT * FROM ExampleTable");
while ($row = mysql_fetch_array($query)) {
echo $row["ColumnOne"];
}
And to the UPDATE query:
UPDATE ExampleTable SET ColumnOne = 'some value'
Usage in PHP is also with mysql_query. You can also use WHERE conditions in the query.
1 - Displaying All Data
<?php
// Conect to MYSQL
$con = mysql_connect("localhost", "My_Username", "My_Password") or die(mysql_error());
echo "Connected to MYSQL </br>";
mysql_select_db("My_Database") or die(mysql_error());
echo "Connected to Database";
// Get all the data from the "ExampleTable" table
$result = mysql_query("SELECT * FROM ExampleTable") or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>ColumnOne</th> <th>CoumnTwo</th> <th>CoumnThree</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['ColumnOne'];
echo "</td><td>";
echo $row['ColumnTwo'];
echo "</td><td>";
echo $row['ColumnThree'];
echo "</td></tr>";
}
echo "</table>";
?>
From: http://www.tizag.com/mysqlTutorial/mysqlselect.php
2 - Data Storage
Anything INSERT-ed into a database will remain* in the database until it is explicitly deleted.
*with few exceptions - but you'll learn about them a little later in your database journey :)

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories