How to randomize the columns in a selected row in PHP - php

The selected id will select the row and randomize. However, it could randomize the same elements.
For example:
'I like to play the piano.'
The output I'm expecting is randomized to eg. ' Play the like to I piano '
But what I receives sometimes turns out to be ' I piano piano like to piano'
This words comes from the database(phpmyadmin). How do I make it such that the data will all appear but not repeat?
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
$x = rand(1,4);
echo "$x";
$y = rand(1,4);
echo "$y";
$z = rand(1,4);
echo "$z";
$c = rand(1,4);
echo "$c";
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo "<dt>Sentence:</dt><dd>" . $row["$x"] . " " . $row["$y"] . " " . $row["$z"] . " " . $row["$c"] ."</dd>";
}

You can do:
//create an array with numbers 1-4
$order = array(1,2,3,4);
//shuffle them in random order
shuffle($order);
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
//Display all the array values from 0-3 (array index starts from 0)
echo "<dt>Sentence:</dt><dd>" . $row[$order[0]] . " " . $row[$order[1]] . " " . $row[$order[2]] . " " . $row[$order[3]] ."</dd>";
}
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Try using the shuffle() function.
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
shuffle($row);
// Write the data of the person
echo "<dt>Sentence:</dt><dd>" . implode(' ', $row) . "</dd>";
}
Unrelated: mysql_* are deprecated as of php 5.5 and will be removed in the future. Use mysqli or PDO instead.

Related

how to get values from sql array, echo them by a defined variable

I want to echo specific values from an selected SQL array, when they are equal to a defined variable.
Here's my defined variables:
$recipe1=1;
$recipe2=2;
$recipe3=3;
My SQL
$cat_sql = "
SELECT feature_id, recipe_id, recipe_name, description, image
FROM feature, recipes
WHERE recipe_id=$recipe[] ";
$result = mysql_query($cat_sql, $con);
$record = mysql_fetch_array($result);
Basically, I want something along the lines of:
<div> echo $recipe1_id; $recipe1_name; $recipe1_description</div>
<div> echo $recipe2_id; $recipe2_name; $recipe2_description</div>
<div> echo $recipe3_id; $recipe3_name; $recipe3_description</div>
I want these values to be echo'd in different places (not part of an array) within tags.
Maybe this:
$result = mysql_query($cat_sql, $con);
while ($record = mysql_fetch_array($result)) {
switch ($record['recipe_id']) {
case $variable1:
// do something
break;
case $variable2:
// do something
break;
case $variable3:
// do something
break;
}
}
However, if you are going to print them regardless, then this should work:
while ($record = mysql_fetch_array($result)) {
echo $record['recipe_id'] . '-' . $record['recipe_name'] . '<br />';
}
To pick up certain rows
$select = array(1, 2, 3);
$cat_sql = "
SELECT feature_id, recipe_id, recipe_name, description, image
FROM feature, recipes
WHERE recipe_id IN (" . implode(',', $select) . ")
";
Note: If this is new code, you should consider using PDO or MySQLI instead of MySQL.

I can't display everything from my table, it only displays the last record

Hey Guys I'm having a hard time printing everything from my table in mysql.
It only prints the last record of the table. Thank you in advance.
Here's my syntax:
//query
$search_query="SELECT offer_no,day,time from offer where subject_id = '" .$search_subject_id ."';";
//execution of query
$result = mysql_query($search_query,$dbhandle);
//fetching result
while ($row = mysql_fetch_array($result)) {
$results =$row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
Output:
1001 MWF 7:00-8:00
Expected Output:
1001 MWF 7:00-8:00, 1002 MWF 8:00-9:00
You need to use either concatenation or array because $results will be reset on each loop and finally takes the last result:
Array:
$results[] =$row['offer_no'] . " " .$row['day']. " " .$row['time'];
Or:
$results .=$row['offer_no'] . " " .$row['day']. " " .$row['time'];
Please note: mysql_* function were deprecated, you can switch to mysqli and PDO and use parametrized query to prevent SQL Injection Attack.
Try this
while ($row = mysql_fetch_array($result)) {
$results[] =$row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
$result_string = "";
if(is_array($results))
{
$result_string = implode(",",$results)
}
echo $result_string;
You have to append each row to a variable, currently, you are overriding the value, leaving only the last one. Try this:
//query
$search_query="SELECT offer_no,day,time from offer where subject_id = '" .$search_subject_id ."';";
//execution of query
$result = mysql_query($search_query,$dbhandle);
$output = "";
//fetching result
while ($row = mysql_fetch_array($result)) {
$output .= $row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
echo $output;
Notice the .= this is shorthand for concatenation of strings to variables.
It always assigns new variable try this one
$results =$results.",".$row['offer_no'] . " " .$row['day']. " " .$row['time'];
let me know if it not work.
Try with $results as an array like
while ($row = mysql_fetch_array($result)) {
$results[] = $row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
You are appending the values to an variable eachtime.So it will holds the last element in the array of mysql_fetch_array for the result.But you need to assign them to an array then it will maintain the assignments of those array elements in the form of an array $result.If you print the $results then you will get the deserver output.
You can also append the results to the $results variable on concating the results like
while ($row = mysql_fetch_array($result)) {
$results .= $row['offer_no'] . " " .$row['day']. " " .$row['time'];
}
echo $results;
And try to avoid mysql_* statements due to the entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_*, is officially deprecated as of PHP v5.5.0 and will be removed in the future.
There are two other MySQL extensions that you can better Use: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql.

Select one value from database

I have the code bellow, it's ok but I want to be able to use for example the 4th value extracted from the database, use it alone, not put all of them in a list, I want to be able to use the values from database individually. How do I echo them?
Edit: I was thinking to simplify things, to be able to add the values from database into one array and then extract the value I need from the array (for example the 4th - ordered by "order_id"). But how?
Right now I can only create a list with all the values one after the other..
(Sorry, I am new to this). Thank you for all your help..
<?php
include '../../h.inc.php';
$con = mysql_connect($db['host'],$db['user'],$db['passwd']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM options WHERE Name LIKE 'x_swift%' ORDER BY order_id");
echo "<table border='1'>
<tr>
<th>Values</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
// echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['VALUE'] . "</td>";
echo "</tr>";
$array = array(mysql_fetch_array($strict));
}
echo "</table>";
mysql_close($con);
?>
To select the value in the value column of the row where order_id is 4, use this SQL:
$query = 'select value from options where order_id = 4';
Then you can access this result in many ways. One is to get the entire result row (which in this case is just one cell) as an associative array:
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
echo 'value = ' . $row['value'];
}
You can also get the value directly:
if ($result = mysql_query($query)) {
echo 'value = ' . mysql_result($result, 'value');
}
It would just be a query like...
$result = mysql_query("SELECT * FROM options WHERE ID = 3");
mysql_fetch_row($result);
Unless Im misunderstanding you....let me know
But you really should use PDO, instead of deprecated mysql_* functions
http://php.net/manual/en/book.pdo.php

PHP: using SQL result in a loop without re-executing query

I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!
If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.
Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}

Combine Multiple rows from mysql array

right guys im having trouble with one.
what i want to do is have a variable which is made from a mysql query. the problem i have is that it needs to contain multiple rows from the query and combine them into one.
currently i have
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow=mysql_fetch_array($lender)) {
$lender1 = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"]
echo '<br />';
}
so basically i want it to take this format if it has multiple rows
blackhorse htfhg125h £250
santander htdhfr58hryf £541
Test 125452asaed2 £760
currently i only get the last result when i echo $lender 1 (obviously because its the last call in the while loop)
Cheers In Advance
You need to use a other array.
<?php
$lender = mysql_query("Select * from lender where reference = '$reference'");
$formated_lender = array();
while ($lenderrow=mysql_fetch_array($lender)) {
$formated_lender = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" .
$lenderrow["amount"];
}
foreach ($formated_lender as $row)
{
echo $row . '<br />';
}
Or, if you would just one variable containing all the row, replace $lende1 = ... by $lender1 .= ...
Just put your echo inside the loop. A loop isn't restricted to one statement.
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow = mysql_fetch_array($lender)) {
$result = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"];
echo $result . "<br />";
}
If you want it in an array, you can use an empty while loop too:
$lender = mysql_query("Select * from lender where reference = '$reference'");
$results = array();
while($results[] = mysql_fetch_array($lender)); // Empty loop
Also, you might want to be careful about SQL injection if $reference is user-supplied and unescaped.

Categories