Load row from MySQL depending on php?id=* - php

I'm fairly new to PHP and MySQL (experienced with other languages). Basically I want to load data from a row relative to its id stated in the URL. Example, load the 3rd row when "index.php?id=3"
Heres what I've managed to do so far: http://pastie.org/1436865
I pretty sure this question has been asked a million times over, but I don't know what term to search far and have not been able to find anything so far :S
Thanks guys

The part id=3... is called query string and you can access it using the $_GET array (see PHP: Predefined Variables).
BTW: It does not make sense to load the 3rd row from a database table, because the rows in the database table do not have an ordering (so instead of a list of rows, a set of records is a more appropriate analogy in this case). Records are usually identified by a so called primary key and you have to make sure yourself, that your database tables have a primary key.

Or if you prefer array's instead of objects try something like this:
$query="SELECT * FROM table WHERE id=".(int)$_GET['id']." LIMIT 1";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row['column'];
}
or if you like indexed columns
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $row[0];
}
or both (column names and indexes):
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
echo $row[0].'-'.$row['column'];
}
You can even use this if you need only one row:
$result = mysql_query("SELECT * FROM table WHERE id=".(int)$_GET['id']);
$row = mysql_fetch_row($result);
echo $row[0];

Based on all these not-so-clear but working examples, you can make a function:
function getRow($query){
$res = mysql_query($query);
if (!$res) {
trigger_error(mysql_error." in ".$query);
return array();
}
$row = mysql_fetch_assoc($res));
if ($row) return $row;
return array();
}
then store it into some library file, then include this file into your script and call with just single line
$data = getRow("SELECT * FROM tablename WHERE id=".intval($_GET['id']));
Also note Oswald's note, it's very important. You can't and you shouldn't rely on the row's relative position as there is no position at all. A DB table is a heap, not ordered list.
Use certain unique field value to address certain row. That's the way to go

The simplest way is
$id = (int) $_GET['id'];;
$result = mysql_query("SELECT * FROM tablename WHERE id=".$id);
while($res = mysql_fetch_object($result)){
echo $res->columnname;
}
Of course, you should check input parameters, etc. This is only approach.

Related

Selecting 4 columns from 3 Random Data From PHP & MySQL

so I'm using the RAND() LIMIT 3, but I use it in a loop to get 3 random rows.
I need to use each column in a different place in my site. How can I grab the data without running a different query for each column?
The data I need shouldn't be in order, so it'll be for example:
$Title, will be the title of the page.
$price, will be the price of the service/product.
$description, will be the description of the service/product.
Clearly, they're not close one to another in the php file.
Both answers sound logical, but I'm totally new to mysql and I can't make it work.
This is what I have in my php file:
<?php
mysql_connect("localhost", "test", "test") or die (mysql_error ());
mysql_select_db("test") or die(mysql_error());
$strSQL = "SELECT name FROM UserId ORDER BY RAND() LIMIT 3";
$rs = mysql_query($strSQL);
while($row = mysql_fetch_array($rs)) {
echo $row['name'] . "<br />";
}
mysql_close();
?>
What it does is return random 'name' column of 3 rows.
The table has 'id', 'name' and 'Age'.
Your help is really appreciated!
Store them in $_SESSION only if they are not already there, and always access them from $_SESSION.
// On every page that uses these values:
session_start();
if (empty($_SESSION['rand_rows'])) {
// DB connection code omitted...
// This block will execute once per session only...
// Get 3 random rows
$strSQL = "SELECT name, id, age FROM UserId ORDER BY RAND() LIMIT 3";
$rs = mysql_query($strSQL);
if ($rs) {
// Fetch all 3 rows and store them in $_SESSION:
while ($row = mysql_fetch_assoc($rs)) {
$_SESSION['rand_rows'][] = $row;
}
}
}
// Later, get them $_SESSION
// To get the name for example:
foreach ($_SESSION['rand_rows'] as $r) {
echo $r['name'] . "<br />";
}
// Use the same looping pattern to get the id or age where you need them.
It still isn't clear if you actually need this to persist across page loads. If you only need these rows on one single page and can get 3 different rows on other pages or subsequent page loads, there's no need to store into $_SESSION and instead just store them into an array with:
// Array to hold all results
$results = array();
while ($row = mysql_fetch_assoc($rs)) {
$results[] = $row;
}
... and use the same foreach pattern to iterate over $results.
If you put the values into variables, such as $title, $price and $description their values will be remembered across the same file, even when using includes.
If you are trying to save the values across different pages, there are different ways of achieving this, although I would probably recommand using $_SESSION to store such information across pages.
If you are doing as first suggested, but without luck, I will need more information to answer your question properly. A small code sample could help.
Edit:
While the answer by #michael-berkowski is fully functional, you don't necessarily have to use $_SESSION to achieve what you want. Since you stated that you're just learning PHP, I've added a different approach. While not as elegant as the other answer, it is faster, and I have edited variables a little (it is a good habit, to use lowercase table names, the same for variables):
<?php
//Insert DB-connection code
$sql = "SELECT `name` FROM `user` ORDER BY RAND() LIMIT 3";
$rs = mysql_query($sql);
//We should check, if there are actually 3 rows, before doing anything else.
if (mysql_num_rows($rs) == 3) {
$title = mysql_result($rs,0,0);
$price = mysql_result($rs,1,0);
$description = mysql_result($rs,2,0);
}
echo("Title: $title <br/>Price: $price <br/>Description: $description");
?>
Good luck learning PHP.

Convert MySQL result to an array strings

I am selecting names of my products from products table in MySQL then I want to present these names to something like $names = array(name1, name2, ...) Where name1, ... are the names of the products from MySQL. I have gone through suggested similar cases but none seems to solve my problem. I am a newbie and just trying to learn.
$result = mysql_query("SELECT name FROM products");
$names=array();
while ($row = mysql_fetch_row($result)) $names[]=$row[0];
mysql_free_result($result);
You need the loop, as there is no way to directly get all rows of the complete result set.
$result = mysql_query("
SELECT `productname` FROM `products`
")or die($result."<br/><br/>".mysql_error());
$numrows = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$productname[$i] = $row['productname'];
// to print out use the following
echo $productname[$i];
$i++;
}
Well, from an academic point of view, I suppose there's a "viable" alternative in doing something like
$names = explode('<|>', mysql_result(mysql_query(
"SELECT GROUP_CONCAT(name separator '<|>') FROM products GROUP BY 'name'"
), 0));
All the power of loops and arrays in single line, for the low, low price of making baby Jesus cry. And yes, you should probably use a loop. Unless you have a phobia ever since a loop waited for you outside your school when you were little and beat you up, I guess.
Dunno why everione sticked to one-liner but anyway it's always good idea to make your code less bloated
create a function
function dbGgetCol($sql) {
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_row($result)) {
$ret[] = $row[0];
}
mysql_free_result($res);
}
return $ret;
}
place it in some config file included into each script
and then get your array with this simple code
$names = dbGetCol("SELECT name FROM products");

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

fastest way to display mysql db records

I have slow query problem, may be i am wrong, here is what i want,
i have to display more than 40 drop down lists at a single page with same fields , fetched by db, but i feel that the query takes much time to execute and also use more resources..
here is an example...
$sql_query = "SELECT * FROM tbl_name";
$rows = mysql_query($sql_query);
now i use while loop to print all records in that query in drop down list,
but i have to reprint same record in next drop down list up to 40 lists, so i use
mysql_data_seek() to move to first record and then reprint the next list and so on till 40 lists.
but this was seems slow to me so i use the second method like this same query for all 40 lists
$sql_query2 = "SELECT * FROM tbl_name";
$rows2 = mysql_query($sql_query2);
do you think that i wrong about the speed of query, or do you suggest me the another way that is faster than these methods....
Try putting the rows into an array like so:
<?php
$rows = array();
$fetch_rows = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_assoc($fetch_rows)) {
$rows[] = $row;
}
Then just use the $rows array in a foreach ($rows as $row) loop.
There is considerable processing overhead associated with fetching rows from a MySQL result resource. Typically it would be quite a bit faster to store the results as an array in PHP rather than to query and fetch the same rowset again from the RDBMS.
$rowset = array();
$result = mysql_query(...);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
// Append each fetched row onto $rowset
$rowset[] = $row;
}
}
If your query returns lots of rows (thousands or tens of thousands or millions) and you need to use all of them, you may reach memory limitations by storing all rows into an array in PHP. In that case it may be more memory-conservative to fetch rows individually from MySQL, but it will still probably be more CPU intensive.
Instead of printing the records, going back, and printing them again, put the records in one big string variable, then echo it for each dropdown.
$str = "";
while($row = mysql_fetch_assoc($rows)) {
// instead of echo...
$str .= [...];
}
// now for each dropdown
echo $str;
// will print all the rows.

Mysql database retrieve multiple rows

I use a mysql database. When I run my query I want to be able to put each row that is returned into a new variable. I dont know how to do this.
my current code:
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution=$row['solution'];
}
?>
The thing is that check num rows can return a row of an integer 0-infinity. If there are more solutions in the database how can I assign them all a variable. The above code works fine for 1 solution, but what if there are more? Thanks.
You can't give each variable a different name, but you can put them all in an array ... if you don't know how this works I suggest looking at a basic tutorial such as http://www.w3schools.com/php/php_arrays.asp as well as my code.
A very simple way (obviously I haven't included mysql_num_rows etc):
$solutions = array()
while($row = mysql_fetch_assoc($result)) {
$solutions[] = $row['solution'];
}
If you have three in your result solutions will be:
$solutions[0] -> first result
$solutions[1] -> second
$solutions[2] -> third
<?php
$result=mysql_query("SELECT * FROM table WHERE var='$var'");
$solution = array();
$check_num_rows=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result))
{
$solution[]=$row['solution'];
}
?>

Categories