i am tryng to select 5 mysql rows from the database and display them like $row[1] ect.... in php i am not sure how to do it an someone lead me down the right way please
Ok i hav looked a bit more
i wanted it to come out 1 - 5 and i wanted it to display the names
$result = mysql_query("SELECT * FROM table ORDER BY id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
$arr = array("somearray" => array(1 => 5, 2 => 9, 3 => 42, 4 => 42, 5 => 42));
echo $arr["somearray"][1];
echo $arr["somearray"][2];
echo $arr["somearray"][3];
echo $arr["somearray"][4];
echo $arr["somearray"][5];
}
I think the OP wants five ROWS, not COLUMNS. Here is the correct code, assuming you already have a mysql connection open:
$sql = 'SELECT *
FROM table_name
ORDER BY col_name
LIMIT 5';
$result = mysql_query($sql);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row[] = $line;
}
// print (access individual rows: $row[0] ... $row[4])
var_dump($row);
From php.net :
http://us3.php.net/manual/en/function.mysql-fetch-row.php
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
Try using MySQL's LIMIT clause to limit your results to 5 rows. And use PHP's mysql_fetch_assoc() (returns an associative array) instead of mysql_fetch_row() (returns a numerically indexed array). Also, it's good practice to free the memory associated with the result using mysql_free_result().
$result = mysql_query("SELECT * FROM mytable ORDER BY id DESC LIMIT 5") or die (mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
echo $name;
}
mysql_free_result($result);
If you only need to select 5 rows from MySQL you can do this:
SELECT *
FROM Table
ORDER BY column
LIMIT 5
Related
How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.
i'm having a slight problem with this mysql query.
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$list = mysql_fetch_assoc($result);
while($list = mysql_fetch_assoc($result)){
echo $list['counter'];
echo "<br>";
}
mysql_free_result($result);
Want i'm wanting to achieve is it listing 5 entrys by order "Counter" But when listing it? it only shows 4 entrys like so :-
5648
4575
1595
35
So where is my 5th entry? and why isn't it posting it? NOTE that the 5th entry is also the highest with a value of
305355
Thanks in advance
You fetch before the loop which pops one record off the result set (i.e. 305355).
$list = mysql_fetch_assoc($result); // REMOVE THIS LINE
while($list = mysql_fetch_assoc($result)) {
// output code
}
Try to reduce the code and use mysqli_ functions
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn);
while($list = mysql_fetch_assoc($result)){
echo $list['counter']."<br>";
}
try out this code..
$sql = "SELECT name FROM videos ORDER BY counter DESC LIMIT 5";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while($list = mysql_fetch_assoc($result)){
echo $list['counter'];
echo "<br>";
}
mysql_free_result($result);
you are calling mysql_fetch_assoc two time that is why your first row get by first time you called the mysql_fetch_assoc and remaining show in second calls
I currently have a table like the one below.
ID adPlacement filePath dateAdded adName adLink
12 1 Test 1.png 2013-02-12 Test 1 http://www.cuad.coop
13 1 Test 2.png 2013-02-12 Test 2 http://www.google.com
I am trying to randomly select a row and echo out the adName, adLink, and filePath all on separate echo statements.
Here is the code I am using right now:
$query_adSpot1 = "SELECT * FROM advertisements WHERE adPlacement = 1";
$result = mysql_query($query_adSpot1, $server) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$row = array(
'adName' => $row['adName'],
'filePath' => $row['filePath'],
'adLink' => $row['adLink']
);
$fileLocation = $row;
$fileLocations[] = $fileLocation;
}
shuffle($fileLocation);
echo $fileLocation[0];
Right now when I run the script it will write test 2.png, or test 2, or http://www.google.com.
I want to be able to echo separately from a random row, but need the separate columns to equal same row.
echo filePath
echo adName
echo adLink
You are shuffling the wrong array, you should be using:
shuffle($fileLocations);
^ This is the one with all your values
var_dump($fileLocations[0]);
// will show you an array with 3 elements from the same row in the database
What you are doing is re-ordering the last row found in your sql query.
You can use the RAND()function in MySQL
$query_adSpot1 = "SELECT * FROM advertisements WHERE adPlacement = 1 ORDER BY RAND() LIMIT 1";
$result = mysql_query($query_adSpot1, $server) or die(mysql_error());
$row = mysql_fetch_array($result);
echo $row['filePath'];
echo $row['adName'];
echo $row['adLink'];
Can anyone tell me why I am not getting the result of displaying the title on the browser when using the following script:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
echo $sql Title;
my connection is successful, but my desired result is not happening.
$sql = mysql_query( "SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 ");
while($row = mysql_fetch_object($sql))
{
echo $row->Title;
echo '<br />';
}
Maybe you can check this link for more example using mysql_query and mysql_fetch_object :
mysql_query: http://php.net/manual/en/function.mysql-query.php
mysql_fetch_object: http://www.php.net/manual/en/function.mysql-fetch-object.php
Your Query is invalid (single quotes are not used for tables / columns):
$result = mysql_query("SELECT Title FROM Tour WHERE Tour_No = 1 LIMIT 1");
You have to fetch the results:
$row = mysql_fetch_assoc($result);
Output the title:
echo $row['Title'];
Table and field names can be put in backtics, not in single quotes.
SELECT * FROM `Tour` WHERE `Tour_No.`=1 LIMIT 0, 30 // correct
SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 // wrong
if your getting 30 results you will need to loop through $sql, try the following.
$sql = mysql_query("SELECT * FROM `Tour` WHERE `Tour_No.` = 1 LIMIT 0, 30 ");
while($row = mysql_fetch_array($sql))
{
echo $row['Title'];
}
From http://php.net/mysql_query:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error....
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data."
Try this:
$sql =mysql_query( "SELECT * FROM 'Tour' WHERE 'Tour_No.'=1 LIMIT 0, 30 ");
$row = mysql_fetch_assoc($sql);
echo $row['Title'];
I'm not sure exactly what your columns are named, but that should get you on the right track.
im just need the easiest way in php to navigate in this result:
$datos = mysql_query("SELECT * FROM
usuarios LIMIT 0, 30 ");
I mean, how do i do an echo from $datos in each element of the table?
Ex.
Table:
ID Name LastName
1 Domingo Sarmiento
2 Juan Lopez
How can i read for example the second last name?
mysql_query, when used for SELECT statements, returns a resource which you can use to return the found rows:
$result = mysql_query("SELECT * FROM usuarios LIMIT 0, 30 ");
while ($row = mysql_fetch_assoc($result)) {
echo $row['ID'];
echo $row['Name'];
echo $row['LastName'];
}
Refer to the linked documentation for additional uses and functions.
Since you are learning PHP/MySQL it would behoove me to point out the preferred method of interacting with databases: PDO. PDO affords a consistent interface to all supported databases with added benefits such as prepared statements and lowered injection risk, to name a couple.
You could try mysql_data_seek
Here's one of the examples from the site:
<?php
$query="SELECT * FROM `team` ORDER BY `team`.`id` ASC";
$result=mysql_query($query);
$last_row = mysql_num_rows($result) - 1;
if (mysql_data_seek($result, $last_row)) { //Set Pointer To LAST ROW in TEAM table.
$row = mysql_fetch_row($result); //Get LAST RECORD in TEAM table
$id = $row[0] + 1; //New Team ID Value
// more code here ...
} else { //Data Seek Error
echo "Cannot seek to row $last_row: " . mysql_error() . "\n";
}
?>
The PHP manual is a good start to use mysql_* functions.
What you are trying to do is loop through your result.
$datos = mysql_query("SELECT * FROM usuarios LIMIT 0, 30 ");
while ($row = mysql_fetch_array($datos, MYSQL_BOTH)) {
printf("ID: %s Name: %s LastName: %s", $row[0], $row[1], $row[2]);
}