Echo a selected id from MySQL table - php

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks

If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}

From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.

mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Related

Retrieve last row in array using end($array)

After doing some research I hear that to retrieve the last row on an array I can use end($arrayname)
However when putting this into my page it does not retrieve the last, but the first in the array.
$query2 = "SELECT * FROM Items";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
$lastElement = end($row2);
echo $lastElement;
}
Looping through the array like this will loop through and display every row in the array one after the other:
Agate & Labradorite Necklace.jpgAgate Necklace.jpgAventurine, Citrine and Carnelian Necklace.jpg
However I was under the impression it should simply repeat the last item (Carnelian necklace.jpg) every time
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = end($row2);
echo $lastElement
This will print the first item in the array. Any ideas what is causing this to happen?
Why to do so much trouble just select the last row in the query as
SELECT * FROM Items order by primary_key desc limit 1
primary_key is the column name of your table which is primary key
You are applying end to $row2, which already represents a row of data. This makes $lastElement be the last column of each row (the while iterates over rows).
It would not make sense to fetch N items just so that you can repeat the last one of them N times (in addition: your SQL query does not specify a sort order, so which item is going to be last is also unknown to you). If you wanted to do something like that you would fetch one item using LIMIT 1 and the number N using an appropriate query and finally simply use a for loop.
Try with array_pop function in php
$row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC);
$lastElement = array_pop($row2);
echo $lastElement
you can try this :
$query2 = "SELECT * FROM Items DESC limit 1";
$resultSet2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($resultSet2, MYSQL_ASSOC))
{
echo $lastElement = $row2;
}

SQL issue within php

Thanks a lot for your answers, they really helped me a lot!
I'm curious of what I'm doing wrong: I can't get any values from a SQL statement.
My database table structure:
My phpcode:
include('config.php');
$id = $_GET['id'];
$query = "SELECT * FROM upload WHERE id = '$id'";
echo $query."<br/>";
$result = mysql_query($query) or die('error');
print_r($result);
echo $result['id'];
I get the following when testing:
"SELECT * FROM upload WHERE id = '1'
Resource id #2"
But there IS an id with value '2', but why doesn't it show in my html?
Only with a 'while' statement I get the desired results:
while($results = mysql_fetch_array($result))
{
echo $results['filetitle'];
}
Is this while statement necessary with a single result? I mean, there can only be one ID.
A resource is a resource. It contains a number of rows. It isn't special-cased for when there is exactly one row returned.
You don't have to use while if you know there is exactly one result, but you still need to use mysql_fetch_array or some other method to extract the first row from it.
$result is a matrix, having each row an output. So to access to id you firstly have to indicate the row.
For example, with $result[ 0 ][ 'id' ].
However, it is quite better to do it through the while($results = mysql_fetch_array($result)) expression.
SELECT statement return Resource ID #, you have to iterate your result using mysql_fetch_array, mysql_fetch_assoc functions.
try with this
$result[0]['id'];

show 2 random rows instead of one

MY SQL QUERY:
$q = mysql_query("SELECT * FROM `ads` WHERE keywords LIKE '%$key%' ORDER BY RAND()");
RESULTS: KEYWORD123
This query searches and results in one random row but i want to show 2 random rows.
How to do that?
any solution?
how??
im grabbing it using this
$row = mysql_fetch_array($q); if ($row
<= 0){ echo 'Not found'; }else{ echo
$row['tab']; }
That query (as-is) will return more than one row (assuming more than one row is LIKE %$key%). If you're only seeing one record, it's possible you're not cycling through the result set, but rather pulling the top response off the stack in your PHP code.
To limit the response to 2 records, you would append LIMIT 2 onto the end of the query. Otherwise, you'll get every row that matches the LIKE operator.
//Build Our Query
$sql = sprintf("SELECT tab
FROM ads
WHERE keyword LIKE '%s'
ORDER BY RAND()
LIMIT 2", ('%'.$key.'%'));
// Load results of query up into a variable
$results = mysql_query($sql);
// Cycle through each returned record
while ( $row = mysql_fetch_array($result) ) {
// do something with $row
echo $row['tab'];
}
The while-loop will run once per returned row. Each time it runs, the $row array inside will represent the current record being accessed. The above example will echo the values stored in your tab field within your db-table.
Remove your order by and add a LIMIT 2
That happens after the execution of the SQL.
Right now you must be doing something like
$res = mysql_query($q);
$r = mysql_fetch_array($res);
echo $r['keywords'];
what you need to do
$q = mysql_query("SELECT * FROM ads WHERE keywords LIKE '%$key%' ORDER BY RAND() LIMIT 2");
$res = mysql_query($q);
while($r = mysql_fetch_array($res)){
echo "<br>" . $r['keywords'];
}
Hope that helps
This query will return all rows containing $key; if it returns only one now this is simply by accident.
You want to add a LIMIT clause to your query, cf http://dev.mysql.com/doc/refman/5.0/en/select.html
Btw both LIKE '%... and ORDER BY RAND() are performance killers

Select multiple values from the same row?

I have a script and I want to return 5 values from the database that have the same category but it is only returning one. Any ideas?
Here's the script:
$result = mysql_query("SELECT Category FROM GameData
WHERE Title=\"$title\" ");
//returns category to search in next select
$row= mysql_fetch_array($result);
$results = mysql_query("SELECT Title FROM GameData
WHERE Category=\"$row[0]\" LIMIT 5 ");
$rows= mysql_fetch_array($results);
print_r($rows); //returns $title from first select query
I'm new to databases and MySQL so any help would be much appreciated.
mysql_fetch_array just fetch one row in one call use loop to fetch multiple records
while($row= mysql_fetch_array($results))
{
print_r($row); //returns $title from first select query
}
You must loop over all the results: mysql_fetch_array returns one result row, so you have to call it multiple times:
while($row = mysql_fetch_array($results)) {
// here process ONE row
}
mysql_fetch_array will only fetch one row : if you want to fetch several rows, you'll have to call mysql_fetch_array several times -- in a loop, typically.
For a couple of examples, you can take a look at its manual page ; but, in your case, you'll probably want to use something like this :
$results = mysql_query("SELECT Title FROM GameData
WHERE Category='...' LIMIT 5 ");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
// work with $row['Title']
}
mysql_fetch_array only returns one row, you would have to loop through the rows
see example at: http://php.net/manual/en/function.mysql-fetch-array.php
You should use following query in order to make things right.
SELECT `Title` FROM GameData
LEFT JOIN
Category ON Category.Id = GameData.Category
WHERE Category.Title = "$title" LIMIT 5
I assumed that Category has column Id.
I advise you to learn about JOINS.
Additionally, you may want to rename Category to Category_Id, and drop letter-case so Category would become category_id.

MySQL MAX(id) called from PHP produces strange value

I am just trying to get the auto incremented value of a table that is currently the highest. I do not need to know what the next auto increment is, just the highest value of what is in the table right now. I am using the code below, but regardless of what the actual auto increment is, what table I last inserted into, what table was last updated / modified, or any other factors that I can see, the value always returns Resource id #4. This is perplexing to me for two reasons. First I don't understand why the number is always 4, second I do not understand why I am getting back a string value (with letters and a symbol) instead of just an integer. What is the deal here?
<?php $highest_id = mysql_query("SELECT MAX(c_id) FROM customers"); ?>
mysql_query doesn't return the value from the query, it returns a result resource. To get the actual value, you need to use one of the mysql_fetch_* functions, passing it the result resource you got from mysql_query.
<?php
$result = mysql_query("SELECT MAX(c_id) FROM customers");
$row = mysql_fetch_row($result);
$highest_id = $row[0];
?>
or the shorter...
<?php
$highest_id = mysql_result(mysql_query("SELECT MAX(c_id) FROM customers"), 0);
?>
This is my answer:
require_once 'db_cconnection.php';
$query = "SELECT MAX(stud_id) FROM student_tbl";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_row($result);
echo $row[0];
When you use mysqli_fetch_row it will fetch only one row, as we only want one row. $row will be an array. So we need to get its value through array index.
mysql_query returns a result handle, not the actual result. In other words, your query's result is saved as resource id #4 (and that's not guaranteed to be the same always, it's coincidence if you see it that way all the time).
To access the result you need to use something like mysql_fetch_array or one of the other functions in the same family.
Something like this:
<?php
$query = mysql_query("SELECT MAX(c_id) as max FROM customers");
$row = mysql_fetch_array($query);
$highest_id = $row['max'];
?>
the 2015 way of doing this
suppose you have database ($this->db)
$maxid = $this->db->query('SELECT MAX(c_id) FROM `customers`')->fetchColumn();
$highest_id = mysql_result(mysql_query("SELECT MAX(c_id) FROM customers"));

Categories