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]);
}
Related
I created folowing view (select list of last active users):
SELECT U.login, U.name, U.surname
FROM sessions S LEFT JOIN user U
ON S.id_user = U.id_user
WHERE U.id_user != 0 AND UNIX_TIMESTAMP()-S.set_time < 300
ORDER BY S.set_time DESC
SELECT *FROM vonline; gives me(i call it in phpmyadmin):
login name surname
admin Chuck Norris
user2 John Cena
I am trying to get same output in php:
if ($stmt = $mysqli->prepare("SELECT * FROM vonline")) {
$stmt->execute();
$result = $stmt->get_result();
echo "Online users: $stmt->num_rows"; // This shows "0"
while ($row = $result->fetch_array(MYSQLI_NUM)) {
echo "Login: $row[1] Name: $row[1] Surname: $row[2]";
}
} else {
echo "Select Error";
}
Why get no results, num_rows returns 0.
The code above works perfectly for selecting data from other tables, but not for this one.
Firstly, you're passing your code inside a string literal, rather than an executable.
echo "Online users: $stmt->num_rows"; // This shows "0"
That should read as
echo "Online users: " . $stmt->num_rows;
and using concatenation.
Example from the manual:
if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
http://php.net/manual/en/mysqli-result.num-rows.php
Change $stmt->num_rows to $result->num_rows which I feel you are using the wrong variable. You need to use the variable on the "result" and the get_result() function.
However, get_result() may not be available for you to use.
Consult this Q&A on Stack:
What's wrong with mysqli::get_result?
As well as the manual http://www.php.net/manual/en/mysqli-stmt.get-result.php
Also make sure you're using the same MySQL API to connect with as your query.
Check for errors also against your db and query:
http://php.net/manual/en/mysqli.error.php
Edit:
This does not help you if there are errors in your query:
else {
echo "Select Error";
}
Change $stmt->execute(); to read as
if(!$stmt->execute()){
trigger_error("there was an error....".$mysqli->error, E_USER_WARNING);
}
Or use
echo("Error description: " . mysqli_error($mysqli));
in your else.
Plus, make sure you did select the right "database".
I have a table in my database named visitor_table . Within table i have a column named visitor_affiliate. I want to get the count of the rows when visitor_affiliate = "someurer" .
I want to get the count as number. I already have this code but i don't know how to get the count only for the rows containing the string. I currently get the number of all rows,
$result = mysql_query("SELECT * FROM visitor_table");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
You can ask MySQL to return the count:
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = 'someurer'
You shouldn't be using the ancient (deprecated as of PHP v5.5.0, soon to be removed entirely) MySQL extension for writing new code—use instead the improved MySQLi extension or the PDO abstraction layer, both of which enable you to pass variables to the database in a safe, parameterised, fashion that ensures they are not evaluated for SQL (and therefore prevents SQL injection attacks):
$dbh = new PDO("mysql:dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$qry = $dbh->prepare('
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = ?
');
$qry->execute(['someurer']);
echo $qry->fetchColumn(), ' rows';
$result = mysql_query("SELECT * FROM visitor_table WHERE `visitor_affiliate` = 'someurer'");
$num_rows = mysql_num_rows($result);
echo $num_rows . " Rows\n";
With what little information you have given just try this-
$result = mysql_query("SELECT * FROM visitor_table Where visitor_affiliate like '%someurer%'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
The deprecated MySQL:
$res = mysql_query('SELECT * FROM visitor_table');
echo 'Number of rows:'.mysql_num_rows($res);
Procedural MySQLi:
$tu = mysqli_prepare($DBH,'SELECT * FROM visitor_table');
mysqli_execute($tu);
$num_rows = mysqli_num_rows($tu);
echo $num_rows.' rows\n';
mysql has been deprecated. Please use mysqli.
Using MySQLi bind_param to get your result:
$someuser = 'Dave';
$DBH = mysqli_connect('localhost','user','pass','database');
$query = mysqli_prepare($DBH,'SELECT * FROM visitor_table WHERE user = ?');
mysqli_bind_param($query,'s',$someuser);
mysqli_execute($query);
mysqli_bind_result($id,$user,$tabCol1,$tabCol2);
while(mysqli_fetch_result){
$row = $row +1;
echo $user.': was found in the record with ID of: '.$id;
}
echo 'total records found:'.$row;
That's one way of doing it as I'm not completely 100% sure about using a mysqli_num_row() with the query above.
I am trying to get pagination working on my website. Everything should be working but this only displays one product, however that should be 8 products. Anybody know what's wrong?
Thanks in advance.
else {
$query = "SELECT COUNT(*) FROM products";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9;
$pages->paginate();
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
{
echo '<div style="margin-bottom:10px;display:inline-block;background-color:#E3E3E3;width:190px;height:200px;"><img style="padding-top:10px;padding-left:25px;width:150px;height:150px;" src="'.htmlspecialchars($row[4]).'"><br><div align="center"><b>'.htmlspecialchars($row[1]).'</b><br><h6>€'.htmlspecialchars($row[3]).'</h6></div></div>';
};
echo ' ';
echo '<br><br><div style="margin-left:330px;">';
echo $pages->display_pages();
echo '</div>';
}
?>
mysql_fetch_row() only fetches one row at a time. You need to call it repeatedly to display all rows, like this:
while ($row = mysql_fetch_row($result)) {
// handle single row
}
I suggest you consider using mysql_fetch_array() instead. Then you will not have to rely on the order of the columns anymore and your code becomes more legible:
$row[0] becomes $row["serial"] etc.
Try reading the articles that #Kush linked. See here for a PHP-specific discussion.
You do not seem to be using mysql_fetch_row() properly
The following code is vulnerable to SQL injection because $page->limit does not appear to be sanitized
$query = "SELECT serial, name, description, price, picture FROM products WHERE serial != '' ORDER BY serial ASC $pages->limit";
Stop using mysql_* functions as they're deprecated. Use PHP database objects (PDO) instead because PDO allows parameter binding which protects you from sql injection.
You can read up on using PDO here
because of this line
$row = mysql_fetch_row($result);
should be
while($row = mysql_fetch_row($result)){...
Change the line
$row = mysql_fetch_row($result);
to
while ($row = mysql_fetch_row($result))
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
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)