Selecting 4 columns from 3 Random Data From PHP & MySQL - php

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.

Related

How do I insert values into an multidimensional-array, then show them?

I'm fairly new to php, and I don't know how to work with arrays very well. Here's the deal, I want to add into a multidimensional array three or more values I obtain from my database, then I want to sort them based on the timestamp (one of the values). After that, I want to show all of the sorted values. I can't seem to do this, here's the code
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, Order, Classification FROM exams WHERE (CurrentState = "Pending")';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if (mysql_num_rows($results) == 0) {
echo '<p>There\'s currently no patient on the waiting list.</p>';
return;
}
while ($rows = mysql_fetch_array($results)) {
extract($rows);
//now is the part that I don't know, putting the values into an array
}
// I'm also not sure how to sort this according to my $TargetTime
asort($sortedTimes);
//the other part I don't know, showing the values,
Thanks for the help!
Well, let's look at your code. First, you have a query that's returning a result set. I don't recommend using mysql_fetch_array because it's not only deprecated (use mysqli functions instead) but it tends to lend itself to bad code. It's hard to figure out what you're referencing when all your keys are numbers. So I recommend mysqli_fetch_assoc (be sure you're fully switched to the mysqli functions first, like mysql_connect and mysqli_query)
Second, I really dislike using extract. We need to work with the array directly. Here's how we do this
$myarray = array();
while ($rows = mysqlI_fetch_assoc($results)) {
$myarray[] = $rows;
}
echo $myarray[0]['ArrivalTime'];
So let's go over this. First, we're building an array of arrays. So we initialize our overall array. Then we want to push the rows onto this array. That's what $myarray[] does. Finally, the array we're pushing is associative, meaning all the keys of the row match up with the field names of your query.
Now, the sorting really needs to be done in your query. So let's tweak your query
$queryWaitingPatients = 'SELECT ArrivalTime, TargetTime, `Order`, Classification
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime';
This way, when your PHP runs, your database now churns them out in the correct order for your array. No sorting code needed.
$arr = array();
while ($rows = mysql_fetch_array($results)) {
array_push ($arr, $row);
}
print_r($arr);
<?php
$queryWaitingPatients = ' SELECT ArrivalTime, TargetTime, Order, Classification, CurrentState
FROM exams
WHERE CurrentState = "Pending"
ORDER BY TargetTime ';
$results = mysql_query($queryWaitingPatients) or die(mysql_error());
if ($results -> num_rows < 1)
{
echo '<p>There\'s currently no patient on the waiting list.</p>';
}
else
{
while ($rows = mysqli_fetch_array($results))
{
$arrivaltime = $row['ArrivalTime'];
$targettime = $row['targettime'];
$order = $row['Order'];
$classification = $row['Classification'];
echo "Arrival: ".$arrivaltime."--Target time: ".$targettime."--Order: ".$order."--Classification: ".$classification;
}
}
echo "Done!";
//or you could put it in a json array and pass it to client side.
?>

Query results stored into one variable

I've read through some other posts that were similar but I can't seem to get a good implementation of them. I'm calling a php script from another program that needs the results returned in one variable, space or comma separated. The php connects to a db (no problem there) and runs a query that will return 2 to 6 or so matching rows. I need those results together in one variable but can't seem to get it.
Here's where I'm stuck.
$t = "SELECT user FROM call_times WHERE client='$clientid' AND start <= $date AND end >= $date";
$result = mysql_query($t) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$temp = $row['user'];
}
echo $temp;
The query runs fine, but you can see from the code what I'm trying (and failing) to do in the lower part. I need $temp to hold a list of results (ex: 5567889 57479992 4335780 (each of which is a different entry in user column)).
Thanks so much!
$array = array();
while ($row = mysql_fetch_array($result)) {
$array[] = $row['user'];
}
$string = implode(" ", $array);
Now $string has the space-separated values of the user column.
Good luck!
Try group_concat() and you won't need PHP to manipulate the results.

MYSQL - Select specific value from a fetched array

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;

How to load a selected cell from sql table PHP

sorry my code is a bit long, please bear with me. i am trying to load the link stored inside a cell from my sql table via php. The user is able to click a checkbox and choose which link to load. however, what i have is a bit off. it loads all the links present in the sql table instead of the one the user chooses. what did i do wrong? please guide. Thank you!
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
$xml = simplexml_load_file($row['bclink']);
}
}
and the HTML is like
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $row['id']; ?>">
OK, a new try with the additional information you gave:
This solution is based on the following assumptions:
The value of the checkboxes you get is in some way related to a field in the database
For the sake of simplicity, I have named that field id - it can be named differently in the database, but only you would know that...
That being said:
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
// in this array, we now have all the values of the checkboxes the user selected
$checkboxvalues = $_REQUEST['checkbox'];
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
// if the ID of this row is mentioned in the checkboxes the user clicked
// then - and only then - load the file
if (in_array($row[id], $checkboxvalues)) {
$xml = simplexml_load_file($row['bclink']);
}
}
}
ok, your code didn't come quite well, it's incomplete.
but for what I can see the $del_record value is the checkbox array with key $i
problem there is that you are calling the database every time, so it's easy to get lost.
you should store the fetched arrays in another array and then iterate there, instead of making lots of requests to the database, that will make your code run faster and you will have more control over it.
I would get SQL to do all the filtering for you:
if (isset($_POST['re_b'])) {
$checkboxvalues = isset($_REQUEST['checkbox']) ? $_REQUEST['checkbox'] : array();
$myCheckboxes = array();
foreach ($checkboxvalues as $cbv) {
$myCheckboxes[] = mysql_real_escape_string($cbv);
}
$sql = "SELECT * FROM previousbroadcast WHERE id IN ('" . implode(",", $myCheckboxes) . "') ORDER BY id DESC";
$result=mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$xml = simplexml_load_file($row['bclink']);
// do something here with $xml or it will get overwritten
}
}

Load row from MySQL depending on php?id=*

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.

Categories