So, after searching for a while here in stack overflow, I found a way of doing it:`
$sql = "SELECT username FROM (SELECT * FROM users ORDER BY id DESC LIMIT 5) sub ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo $row[0];`
However when I echo the $row[0] to get the first entry it doesn't display anything. I have checked my connection to the database and used the query on the phpmyAdmin and it worked fine, not sure why isn't it displaying the data (There is also a user in the table with the ID 1).
mysqli_fetch_assoc returns an associative array, not a numbered array. So the index of each column in the result is the column name, $row['username'].
If you want all 5 usernames, you need to call it in a loop. Each call just returns one row of the results, not all of them at once.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . '<br>';
}
To get a numbered array you use mysqli_fetch_row(). You still need the loop to get all of them.
while ($row = mysqli_fetch_row($result)) {
echo $row[0] . '<br>';
}
Related
I am trying to display some values from a database, and having some issues displaying the correct info.
In my database, there is a column called coplevel that column has enum values upto 7.
In my PHP side of things, I am trying to count all the user's in the database who have a coplevel > 0 but the thing's I have tried on SOF, work but not how I want it to work.
So if I have 5 user's with a cop level of 1,2,3,4,5 I want to count only the users who're coplevel is more than 0
<?php
$sql = "SELECT COUNT(*) FROM `players` WHERE `coplevel` > 0";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$totalc = $row['0'];
echo "<b>" . $totalc . "</b>";
}
mysqli_free_result($result);
} else {
$totalc = "Couldn't find cop info";
}
} else {
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
?>
If there is 5 user's who all have a coplevel over 0, then count and display only the ones who have > 0 as their coplevel
Your query is correct, but you are messing up with the $row array.
This:
while ($row = mysqli_fetch_array($result))
Will return the rows into an associative array called $row
An Associative array stores pairs of KEYS and VALUES
In this case, the key is the column name and the value is the data in the column.
You can access a value in the array either with its index in the array, or with its key name.
When you say :
$totalc = $row['0'];
You try to get the value of the array for which the key is named 0, but it doesn't exist
What you want to do, is getting the index 0. So you should say :
$totalc = $row[0];
A clearer alternative is to alias properly your COUNT(*) in the query, in order to have a proper name for its key in your array :
$sql = "SELECT COUNT(*) AS cnt FROM `players` WHERE `coplevel` > 0";
if ($result = mysqli_query($link, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$totalc = $row['cnt'];
I'm trying to create an image gallery with a for loop iterated by a counter of database rows.
To make it more clear: for each row in the table, get only the id(primary index) number and the image link from the server (not all the info in the row). With that information, echo an HTML image tag with the link inside the 'src=' and the id inside the 'alt='.
Two problems here:
1- the id number of the first row isn't zero.
2- I don't have a clue on how to get the total number of rows and to fetch only those two informations (id and img source).
That way, I could subtract the total number of rows minus the id number of the first row and using it to put an end on the loop.
So how to echo this dynamic html snippet based on my databse with PHP?
My code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$result = mysqli_query($link, "SELECT * FROM `table`");
$rows = mysqli_num_rows($result);
/* free result set */
mysqli_free_result($result);
$caption = mysqli_query($link, "SELECT ");
for($i=0; $i < $rows; $i++) {
echo "<img src='$imageURL' alt='$idNumber'>";
}
?>
You need to use sql functions to iterate through the dataset results. Replace your for loop... replacing 'image_url_column' and 'id_number_column' with the name of your actual columns in your db:
while ($row = while ($row = mysqli_fetch_assoc($caption)){){
echo "<img src='".$row['image_url_column']."' alt='".$row['id_number_column']."'>";
}
This is a really easy task.
First we fetch the data from the database using mysqli_query to do the query.
Then we use mysqli_fetch_array to get an array so then we can loop through it and echo each item.
After that, we mysqli_num_rows to get the total number of rows returned and increment it by 1 so it is not zero.
NOTE: Since you are going to increment the id to avoid getting a '0', don't to forget to minus '1' if you intend to use that id for some server-side purpose.
$result = mysqli_query($link, "SELECT * FROM `table`"); //query sql
$result_array=mysqli_fetch_array($result, MYSQLI_ASSOC);//return array from the query
$count = mysqli_num_rows($result); //get numbers of rows received
foreach($result as $row){ //do a foreach loop which is really simple
echo "<img src='". $row['img_column_name_from_db'] . "' alt='" .$row['id_column_name_from_db'] + 1 . "'>"; //echo data from the array, + 1 to "$row['id_column_name_from_db']" so that 'alt=' doesn't start from '0'.
}
echo $count;
You can use the count function of MySql to achieve the total number of rows.
also you can do this via mysqli_num_rows() function of mysql.
Code:
<?php
$link = mysqli_connect('localhost','user','pass','db');
$caption = mysqli_query($link, "SELECT id, img, count(id) as total from table");
echo
//$rows = mysqli_num_rows($result);
while($rows = mysqli_fetch_assoc($caption)){
echo "<img src='$rows[img]' alt='$rows[id]'>";
echo "Total Rows: ".$rows[total];
}
?>
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'];
}
$sql = "SELECT title, article, filename, caption FROM articles
INNER JOIN images WHERE articles.image_id = images.image_id";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
var_dump($row);
This only grabs the first row in the db when what I need is for it to grab all rows. How can I achieve this?
fetch_assoc() returns the next row of the result set with each call, so you need to call it in a loop like this:
while($row = $result->fetch_assoc()) {
var_dump($row);
}
The loop ends when $row = null (i.e. there's no more rows in the result set).
Please have a look at the Quick start guide, more specifically the Executing statements chapter. Right from that page:
$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$res = $mysqli->use_result();
echo "Result set order...\n";
while ($row = $res->fetch_assoc()) {
echo " id = " . $row['id'] . "\n";
}
Pretty new to all this, so if I am going about my puzzle in a crazy way please tell me!
I have a table in a mySQL database with the columns title, hyperlink, imagelink
I want the php to select a row at random, then be able to save the title, hyperlink and imagelink as php variables. (so I can then output them into html)
so I could have for e.g
psuedoey code to get the idea
chosenNumber = randomNumber();
$chosenTitle = title[chosenNumber]
$chosenHyperlink = hyperlink[chosenNumber]
$chosenImagelink = imagelink[chosenNumber]
echo "<a href = $chosenTitle><img src= $chosenImagelink/> $chosenTitle </a>";
I think I need to use an assoc array like this here but I am very confused, because I looked through the various php mySQL fetch_assoc fetch_row etc and can't find which one to do what i need :(
What I have so far is
// database table name information
$number = "number";
$title = "title";
$hyperlink = "hyperlink";
$imagelink = "imagelink";
// sql to select all rows of adverts
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table";
//execute the sql
$data = mysql_query($sql, $link);
//count the number of rows in the table
$bannerCount = mysql_num_rows($data);
//generate a random number between 0 and the number of rows
$randomNumber = mt_rand(0, $bannerCount); //do I need to do bannerCount-1 or similar here?
$chosenNumber = $randomNumber;
//select data from a random row
First time post, be kind please, and thanks for any replies or explanations!
Using ORDER BY RAND() LIMIT 1 is a decent way to get a single row out of a smaller table. The downside to using this method is that RAND() must be calculated for every row in the table, and then a sort must be performed on this non-indexed value to calculate the row you want. As your table grows, ORDER BY RAND() becomes horribly inefficient. The better way to handle this is to first get a count of the number of rows in the table, calculate a random row number to read, and use the LIMIT [offest,] count option on your SQL query:
$sql = "SELECT COUNT(*) as rows FROM $table"
$res = mysql_query($sql);
if (!$row = mysql_fetch_assoc($res)) {
die('Error Checking Rows: '.mysql_error());
}
$rows = $row['rows'];
// now that we know how many rows we have, lets choose a random one:
$rownum = mt_rand(0, $rows-1);
$sql = "SELECT number, title, hyperlink, imagelink FROM $table LIMIT $rownum,1";
$res = mysql_query($sql);
$row = mysql_fetch_assoc($res);
// $row['number'] $row['title'] etc should be your "chosen" row
This first query asks the SQL Server how many rows are available, then LIMITs the result set of the actual query to only return 1 row, starting at the random number row we picked.
I think if you use the "limit" clause, it would be quite efficient:
SELECT number, title, hyperlink, imagelink FROM $table order by rand() limit 1
Why do you set up variables for the table name and field names?
If you want to get records randomly, you can simply modify your sql query and each time you will get random ordering of records, just add order by rand() to your query and limit clause if you want to get just one random record:
$sql = "SELECT $number, $title, $hyperlink, $imagelink FROM $table
order by rand() limit 1";
Once you have done that, you need to use functions like mysql_fetch_array or mysql_fetch_object to get the rows actually:
$data = mysql_query($sql, $link);
while ($row = mysql_fetch_array($data))
{
echo $row['title'] . '<br />';
echo $row['hyperlink'] . '<br />';
echo $row['imagelink'] . '<br />';
}
With:
$row = mysql_fetch_array($data)
You have $row array available at your disposal to echo values at any place of your page like:
echo $row['title'];
echo $row['hyperlink'];
echo $row['imagelink'];