SQL SELECT * returns only one row - php

I'm designing a website and I wrote some webpage that display the list of users.
I used to do a
$query = SELECT * FROM `table_users` WHERE `id`='.$id.'
and then increment the ID with a "while" so I can grab all the users. But it's too slow now, and it glitches when there is a gap between IDs.
So I tried something like
$query = SELECT `name` FROM `tbl_user`ORDER BY `id`
and displaying the userlist with a
while ($i < sizeof(mysql_fetch_array(mysql_query($query)))){
<code to display an user>
$i++
}
But the mysql_fetch_array only returnes one user, the first one (the one with the littliest ID). I want it to return all users in an array. How do I do ?

Try This
$query = "SELECT `name` FROM `tbl_user` ORDER BY `id`";
$user_query = mysql_query($query);
$i=1;
while ($row = mysql_fetch_array($user_query)){
echo $i." : ".$row['name']."<br>";
$i++;
}

Try it like this:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//$row is the row which was just gathered
}
And please, use PDO or MySQLi instead of deprecated mysql.

Related

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";

Sorting/Limiting Table List MySQL and PHP

I want to make select and print out all of the tables I have (I got that so far), and then limit it using `` and then ordering them by table name, and have 10 results per page.
How would I go about doing that? I know how to do it getting data from tables, but I don't know how to do it using just tables.
I have this so far:
function list_tables($type){
$sql = "SHOW TABLES FROM example";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_name = $row[0];
echo $table_name; //edited out a lot to keep it simple
//I'm just printing out a lot of data based on table name anyway
}
mysql_free_result($result);
}
So far, it only prints out all of the table names (+ extra info I print for table names) all in the same page and it's getting the the point where it takes forever to scroll. I'd like to limit it to about 10-20 posts per page instead of a few hundred posts on one page.
Thanks in advanced if anyone can help me. Much appreciated.
Calculate the offset and limit according to the page number and try the below query:
function list_tables($type, $offset, $limit){
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'example' ORDER BY TABLE_NAME LIMIT $offset, $limit";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)){
$table_name = $row[0];
echo $table_name; //edited out a lot to keep it simple
//I'm just printing out a lot of data based on table name anyway
}
mysql_free_result($result);
}
Use below given query which supports LIMIT so you can do pagination with your table names.
select * from information_schema.tables LIMIT 5
i did this:
function list_tables(){
$amtperpage = 15;
$sql = "SELECT COUNT(TABLE_NAME) FROM information_schema.tables WHERE TABLE_SCHEMA = 'my_dbname'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total_rows = $row[0];
//pagination stuff here
if(isset($_GET['p'])) $curpage = intval($_GET['p']); else $curpage=1;
$start = abs(($curpage-1)*amtperpage);
$sql = "SELECT TABLE_NAME FROM information_schema.tables ORDER BY TABLE_NAME ASC LIMIT $start,$per_page";
$res = mysql_query($sql);
while($row=mysql_fetch_array($res)) $DATA[++$start]=$row;
$uri = strtok($_SERVER['REQUEST_URI'],"?")."?";
$tmpget = $_GET;
unset($tmpget['p']);
if($tempget){
$uri .= http_build_query($tmpget)."&";
}
$num_pages=ceil($total_rows/$amtperpage);
for($i=1;$i<=$num_pages;$i++) $PAGES[$i]=$uri.'p='.$i;
?><div id="container">Pages:
foreach ($PAGES as $i => $link){
if($i == $curpage){
=$i
} else {
?><?=$i?>
}
} ?>
foreach($DATA as $i => $row){
$table_name = $row[0];
//use my functions to get data for each table name and list it and such
}
}
this is highly butchered since I have a lot of stuff that would've gotten in the way of the point but this should work. Thanks to the people who helped me. :)

MySQL - Batch rename all rows in PHP

So in this piece of code, I just deleted a row from the table, and so, the values for img_pos were:
1,2,3,4,5
And now, they are (assuming we deleted the third entry):
1,2,4,5
Of course, I want this to be:
1,2,3,4
So I have to batch rename the rows.
I got this, but doesn't seem to work....
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
$i = 0;
$n = 1;
while($i<$num){
$sql = "SELECT * FROM $tableImg WHERE img_acc = $accid ORDER BY img_pos DESC LIMIT $i,1";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$img_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = '$n' WHERE img_acc = '$accid' AND img_pos = '$img_pos'";
$res = mysql_query($sql);
$i++;
$n++;
}
mysql_close();
$tableImg is just a variable containing the table name, that works just fine.
I guessthe problem is somewhere around "$img_pos = $row['img_pos'];", because all the querys are used somewhere differently, be it slightly different, and they should work...
Thanks in advance!
I ended up simply doing this:
$i = 1;
while($row = mysql_fetch_array($res)){
$old_pos = $row['img_pos'];
$sql = "UPDATE $tableImg SET img_pos = $i WHERE img_acc = $accid AND img_pos = $old_pos";
$res = mysql_query($sql);
$i++;
};
This is quite possible, just totally unnecessary. The nice thing about digital data is that you don't have to look at it so it doesn't matter if it's a bit gappy, does it?
If you REALLY want to do this (say, you are building an application and you are just cleaning up the stuff you deleted whilst working on it) the following example will do in in SQL, as this simple example shows:
CREATE TABLE disorder (id int,stuff CHAR(6));
CREATE TABLE disorder2 (id SERIAL,stuff CHAR(6));
INSERT INTO disorder (id,stuff)
VALUES
('1','ONE'),
('2','TWO'),
('3','THREE'),
('4','FOUR'),
('5','FIVE');
DELETE FROM disorder WHERE id='3';
INSERT INTO disorder2 (stuff) SELECT stuff FROM disorder;
TRUNCATE TABLE disorder;
INSERT INTO disorder SELECT * from disorder2;
DROP TABLE disorder2;
This can be seen in action on sqlfiddle but it's pretty obvious. If you do a SELECT * from disorder, you will see why you probably shouldn't do this sort of thing.
Your tables really do need to have primary keys. This speeds searches/indexing and makes them useful. Look up database normal forms for a thorough discussion of the reasoning.

Printing Duplicate Records In PHP / Mysql

I am trying to print the duplicate records of the table but only the single row is getting
echoed.However in mysql this query results all the duplicate records. Here is the query:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
$r = mysql_fetch_array($q);
$s = mysql_num_rows($q);
while($s !=0)
{
echo $r;
$s=$s-1;
}
Whats wrong with the code?
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
while($r = mysql_fetch_array($q))
{
print_r($r);
}
You need to loop through the entire record set... you are only grabbing the first row:
$resultset = mysql_query("select * from add where cust_id = '144' group by cust_id");
while($row = mysql_fetch_assoc($resultset))
{
echo $row['column_name'];
}
Your SQL query will in practice only ever return 0 or 1 rows, due to the GROUP BY clause. Are you absolutely sure that that's the query you were executing in mysql?
well, if you want to get duplicate values, then this query will serve you well:
T = the table
f = the field to check for duplicates
id = the rows id
select id,f from T group by f having count(f)= 2;
or >2 if you want every value in f that occurs in more than one row.
having is like where but evaluated after group by.
Try the following:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144'");
while($r = mysql_fetch_array($q))
{
echo $r;
}

Simple way to read single record from MySQL

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 :)

Categories