PHP & MYSQLI selecting MySQL Table for Shop Items - php

For my school I need to Select items from the MySQL Server and it only should show the name and the price.
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
$row = mysqli_fetch_array($query);
foreach($row as $values)
{
echo "<p>".$values["item"]."</p>";
echo "<p>".$values["price"]."</p>";
}
I only got something like:
L
L
L
L
4
4
4
4
Its the only first item in the table but there are many rows in DB.

you're doing fine, but what you're doing wrong is, you're picking just one item and iterating over that single value.
Here you're extracting only LLLL4444 and looping on this only, so, in order to get all.
You need to do this.
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row["item"]."</p>";
echo "<p>".$row["price"]."</p>";
}

Try this:
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
while ($row = mysqli_fetch_assoc($query)) {
echo "<p>".$row["item"]."</p>";
echo "<p>".$row["price"]."</p>";
}

mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.
So using mysql_fetch_array() without specifying MYSQL_ASSOC or MYSQL_NUM, or by specifying MYSQL_BOTH will return two arrays

Related

Retrieving the Last ID from the Database from a Specified Category in String Value

I am trying to retrieve the last ID from the database and increment it by one. My problem is that I am not able to retrieve it in a particular category. For instance, I have categories with a string value of A, B and C. The category with a string value of A will return only id starting from 1 as 10001, 10002 and the last ID to be retrieved is 10002 plus 1 so that the ID to be displayed is 10003.
Category "B" will return 20002 and category "C" will return 30002.
Here is my code:
<?php
$con = mysql_connect("server","username","password","db_name") or die (mysql_error());
mysql_select_db($con, 'db_name');
$sql = "Select `id` from `tbl_violation` WHERE `category` = 'A' ORDER BY `category` DESC LIMIT 1";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result, $con))
{
$i = $row['id'];
$i++;
echo "DLR - " .$i;
}
?>
The error is this:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in ...
Notice: Undefined variable: i in ...
First I must say again... Stay away from mysql_connect() and all other mysql_* functions. If you want a simple fix, just replace it with mysqli_ functions and make sure you escape ALL user provided input. A bit of reading But I would recommend to look into PDO.
That out of the way, your MYSQL problem is easy. You want to GROUP the elements so all the rows with same category column are groupped together and then select the maximum for each group. Your SQL would then be:
SELECT category, MAX(id) AS highest_id FROM tbl_violation GROUP BY category;
see this fiddle I made with a similar table.
You can then access the results you get from mysqli_query function the same way you do now...
while($row = mysqli_fetch_array($result, $con))
{
$i = $row['highest_id'];
$i++;
$category = $row['category'];
echo "$category - $i";
}
You can use SELECT MAX to get the highest id. I am assuming that id is not unique. If so, remove the WHERE statement from the query. Try the following.
<?php
$con = mysql_connect("server","username","password","db_name") or die (mysql_error());
mysql_select_db("database");
$sql = "Select MAX(`id`) from `tbl_violation` WHERE `category` = 'A";
$result = mysql_query ($sql,$con);
while($row = mysql_fetch_array($result))
{
$i = $row['id'];
echo "DLR - " .$i++;
}
?>
Also I would like to add that I agree with flynorc. Use PDO or mysqli.
Use
ORDER BY `id` DESC
Instead of
ORDER BY `category` DESC

array in foreach loop

I'm taking data from mysql database table. The table have ID and "POST" columns. I've ordered posts by id's from bottom so i always have the newest post on the first place. But when i want to echo specific post (eg. with id 5) i can't echo it with $col = mysqli_fetch_array($result); echo $col;. I've tried with foreach loop but it echo's all posts. So I thought if i could put them into array with foreach loop it would do the job.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
}
I've tried a lot of things and spent a lot of time on research but still don't have idea how to do it.
Thanks for your ideas and help.
$sql = "SELECT * FROM `post` ORDER BY `id` DESC";
$result = mysqli_query($con, $sql);
$col = mysqli_fetch_array($result);
foreach($col as $cols) {
if($col['id'] == 5) {
print_r($col);
}
}
mysqli_fetch_array fetchs a result row as an associative, a numeric array, or both.
You need to specify the name of the column you want to print out.
Because you may have more than one row in your result set, you should use a loop (while) like so:
while ($row = mysqli_fetch_array($result)) {
echo $row['POST']; // 'POST' here is the name of the column you want to print out
}
Hope this helps!
UPDATED:
If you want to get a specific post, you have to change your SQL to something like this:
$sql = "SELECT * FROM `post` WHERE `id` = $wanted_post_id";

incorrect result display from database

I have a database table that has 4 records with a column _id that auto increments. When I run a query to get all records, it works but it doesn't echo out all the ids, it only points to the first rows and echos it four times. I am using PHP and MySQLi. Here is my code
Code for querying
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
Code for display
do{
echo result['_id'];
}while($query->fetch_assoc());
It outputs 1111 instead of 1234. Please what is wrong?
You're fetching each of the 4 results, so it loops the appropriate number of times; but you're only assigning the fetched result to $result once, so that's the only _id value that gets echoed
do{
echo $result['_id'];
}while($result = $query->fetch_assoc())
You also can use a foreach loop :
$sql = "SELECT * FROM att_table";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
foreach($result as $data){
echo $data['_id'];
}

Accessing two different tables for one loop

I have a small issue that I can't figure out.
I have to pull data from two different tables, in one loop. I've never done that before, so I have no idea how. I tried two different queries. That looked like this:
$query = "SELECT * FROM colors ";
$color_select = mysqli_query($connection, $query);
$second_query = "SELECT * FROM votes";
$vote_select = mysqli_query($connection, $second_query);
And then put them into a loop:
while($row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select))
{
$color = $row['Colors'];
$votes = $second_row['Votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
But that didn't work. I didn't expect it to, just wanted to try. :) Maybe someone experienced can help me out. Thanks.
At the end of the day I need a table displayed, that has two columns, one of them contains the color name from one DB table and the other one contains a number of votes.
As requested: table structures.
Table: colors has only one field Colors.
Table: votes has four fields city_id, City, Colors and Votes
*************************EDIT**************************************
So fixed up the query as suggested, but is still shows nothing.
Here is the edited code:
$query = "SELECT * FROM colors,votes WHERE colors.Colors=votes.Colors";
$color_votes_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_votes_select))
{ $color = $row['Colors'];
$votes = $row['Votes']; }
if table having relation.
try this in single query .
SELECT
`colors`.*,votes.*
FROM
`colors`
INNER JOIN
`votes` ON
`votes`.colorId = `colors`.Id
Most imp *****You should have some relationship between tables
Otherwise workaround
Run query on color, Save it in ArrayA
Run query on vote, Save it in ArrayB
Create New Array ArrayC
$arrayC = array();
Loop array A or C if they both contact same row count
array_push($ArrayC, key and value of color, key and value of votes);
Final loop ArrayC to print tr and td
First Relate These two tables, write color_id in votes table.
$query = "SELECT * FROM colors,votes where colors.id=votes.color_id";
$color_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_select))
{
$color = $row['Colors'];
$votes = $row['Votes'];
}
Try this:
$query = "SELECT colors FROM colors";
$color_select = mysqli_query($connection, $query) or die (mysqli_error());
$second_query = "SELECT votes FROM votes"; //you only need column votes right?
$vote_select = mysqli_query($connection, $second_query) or die (mysqli_error());;
while( $row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select)){
$color[] = $row['colors'];
$votes[] = $second_row['votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
Short explanation:
It will fetch the select and store into an array (because what you were doing is selecting multiple rows into one single variable) and then just display with the echo.

Using a php function in a while loop to get the values and the counts of the values in same column

I am trying to perform a query inside a while loop that is getting values from a column. I am trying to query first to get all my values from a column in my DB and then get the count of how many times that value is in that column.
Examples of output trying to get
myValue is in the column 3 times
myOtherValue is in the column 10 times
myOtherOtherValue is in the column 22 times
Example of code
$sql = "SELECT DISTINCT id, columnName FROM tableName";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
function myCount($id)
{
$query = "SELECT COUNT(*) FROM tableName WHERE name = '$id'";
$result = mysql_query($query);
$count = mysql_fetch_array($result);
}
echo "$id is in the column $count[0] times";
}
You can't define a function inside the while loop.
Using COUNT(*) with a GROUP BY name clause, then you could solve the problem with only one query.

Categories