Create a randomized assoc array from database table results - php

I am creating a simple drag and drop jquery game and it requires a shuffled resultset of 10 rows from my database table. I am able to achieve this by repeating 10 separate blocks of queries, but I am sure there must be a more elegant way to do this. I tried many things, with loops and append etc. but I can't get the loop-way working.
I can't get this loop version to work:
<script type="text/javascript">
<?php
// first create list of 10 fake id's and shuffle them
$id_array = range(0, 9);
shuffle($id_array);
/*
// then loop to fetch all data from MySql table with spanish, english
// CANNOT GET THIS WORKiNG ?
for (i = 0; i < 10; i++) {
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[i]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$rand_value.append(i) = $row['english'];
$name.append(i) = strtoupper($row['spanish']);
}
*/
Writing it out works, but there must be an easier way...
<script type="text/javascript">
<?php
// create all input from MySql table for drag and drop area with spanish, english
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[0]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key0 = $row['id'];
$rand_value0 = $row['english'];
$name0 = strtoupper($row['spanish']);
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[1]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key1 = $row['id'];
$rand_value1 = $row['english'];
$name1 = strtoupper($row['spanish']);
// and so on to run 10 queries total
?>

Simplify everything by using RAND() in your query. Use just one query and retrieve all ten rows in a shuffled order.
$query="SELECT id,english,UPPER(spanish) FROM colors ORDER BY RAND() LIMIT 10;";
$result=mysqli_query($link,$query);
while($row=mysqli_fetch_array($result)){
// prepare and handle your results using: $row['id'], $row['english'], $row['spanish']
}
EDIT: I've added UPPER() to the query so that the spanish values don't need to be modified later in your php.

Related

Placing single column database values into an array then calling them in another query

I'm having trouble with pulling database information from 'rownum' column and putting it into an array and then using that array information for my next query that randomly selects one line of the array and then displays it.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$row' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$row';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
I'm not sure what I have done wrong? Does the array have to be echoed and then my $query line calls that instead?
Updated code - Solved my problem
Thanks for tips guys, it helped me wrap my head around it and came up with a working solution.
<?php
// Connect to database
include 'DB.php';
$con = mysqli_connect($host,$user,$pass);
$dbs = mysqli_select_db($databaseName, $con);
// Select Rownum to get numbers and only where there is no value in seen.
$firstquery = "SELECT rownum FROM num_image WHERE seen=''";
// If there are results store them here
$result = mysqli_query($firstquery) or die ("no query");
// Put the results taken from the table into array so it displays as: array(56, 44, 78, ...) etc...
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
$result_array[] = $row;
}
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
//pick a random point in the array
$random = mt_rand(0,count($all_rownums)-1);
//store the random question
$question = $all_rownums[$random];
// Select the data I require
$query = mysqli_query("SELECT number, association, image_file, skeleton, sound, colour, comments FROM num_image WHERE rownum='$question' LIMIT 1;");
$test = mysqli_query("UPDATE num_image SET Seen='yes' WHERE rownum='$question';");
// Fetch Results of Query, Ignore test.
$arrayss = mysqli_fetch_row($query);
// Echo Results as a Json
echo json_encode($arrayss);
?>
This part is what helped me solve it:
for ($i = 0; $i < count($result_array); $i++) {
$all_rownums[] = implode(',', $result_array[$i]);
}
Happy Dance

mysql_query function only works with mysql_num_rows

I have a very strange problem today. I have a section of code which queries a table based on a GET variable passed from a user input (pretty standard).
However for this to work I have to include a redundant mysql_num_rows variable....
This Works;
<?php
1. $cat = strval($_GET['c']);
2. $query = "SELECT * FROM stock WHERE Category = '$cat'";
3. $num_rows = mysql_num_rows(mysql_query($query));
4. $values = mysql_query($query);
?>
For some reason without line 3 it doesn't work.
By the way this is ultimately used to create an array passed to a google chart which is all fine.
What am I doing wrong?
All code for reference;
<?php
$cat = strval($_GET['c']);
$query = "SELECT * FROM stock WHERE Category = '$cat'";
LINE UNDER QUESTION --> $num_rows = mysql_num_rows(mysql_query($query));
$values = mysql_query($query);
$material = array();
$quantity = array();
$colour = array();
while ($row = mysql_fetch_array($values)) {
array_push($material, $row['Material']);
array_push($quantity, $row['Quantity']);
array_push($colour, $row['Colour']);
}
...Then all the google chart stuff....
?>
Specify columns in the select and use an index.
And make sure the $_GET value is validated.
You probably already have done this, but try the query in e.g. phpMyAdmin.
Maybe all this will help.
SELECT
material,
quantity,
colour
FROM
stock
WHERE
Category = ...
ORDER BY ..
;

Displaying data from database in an unordered list using a loop

I always had trouble understanding how to properly generate unordered lists using loops. But now I gotta generate one and insert data from my database into it. This is how I retrieve the data from my database.
$sql_history = "SELECT * FROM transaction_summary WHERE transaction_Sender='$username' OR transaction_Recipient='$username' ORDER BY id DESC LIMIT 10";
$query = mysqli_query($db, $sql_history);
$row = mysqli_fetch_array($query);
$sender = $row['transaction_Sender'];
$recipient = $row['transaction_Recipient'];
$amount = $row['transaction_Amount'];
How would I display the lastest 10 rows in an unordered list? Thank you.
$row = mysqli_fetch_array($query);
The above line assigns the first record to an array named $row. You need to do this action for EVERY record that your query returned. So you should do:
while($row = mysqli_fetch_array($query))
{
$sender = $row['transaction_Sender'];
$recipient = $row['transaction_Recipient'];
$amount = $row['transaction_Amount'];
}

Accessing two different tables for one loop

I have a small issue that I can't figure out.
I have to pull data from two different tables, in one loop. I've never done that before, so I have no idea how. I tried two different queries. That looked like this:
$query = "SELECT * FROM colors ";
$color_select = mysqli_query($connection, $query);
$second_query = "SELECT * FROM votes";
$vote_select = mysqli_query($connection, $second_query);
And then put them into a loop:
while($row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select))
{
$color = $row['Colors'];
$votes = $second_row['Votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
But that didn't work. I didn't expect it to, just wanted to try. :) Maybe someone experienced can help me out. Thanks.
At the end of the day I need a table displayed, that has two columns, one of them contains the color name from one DB table and the other one contains a number of votes.
As requested: table structures.
Table: colors has only one field Colors.
Table: votes has four fields city_id, City, Colors and Votes
*************************EDIT**************************************
So fixed up the query as suggested, but is still shows nothing.
Here is the edited code:
$query = "SELECT * FROM colors,votes WHERE colors.Colors=votes.Colors";
$color_votes_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_votes_select))
{ $color = $row['Colors'];
$votes = $row['Votes']; }
if table having relation.
try this in single query .
SELECT
`colors`.*,votes.*
FROM
`colors`
INNER JOIN
`votes` ON
`votes`.colorId = `colors`.Id
Most imp *****You should have some relationship between tables
Otherwise workaround
Run query on color, Save it in ArrayA
Run query on vote, Save it in ArrayB
Create New Array ArrayC
$arrayC = array();
Loop array A or C if they both contact same row count
array_push($ArrayC, key and value of color, key and value of votes);
Final loop ArrayC to print tr and td
First Relate These two tables, write color_id in votes table.
$query = "SELECT * FROM colors,votes where colors.id=votes.color_id";
$color_select = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($color_select))
{
$color = $row['Colors'];
$votes = $row['Votes'];
}
Try this:
$query = "SELECT colors FROM colors";
$color_select = mysqli_query($connection, $query) or die (mysqli_error());
$second_query = "SELECT votes FROM votes"; //you only need column votes right?
$vote_select = mysqli_query($connection, $second_query) or die (mysqli_error());;
while( $row = mysqli_fetch_assoc($color_select) && $second_row = mysqli_fetch_assoc($vote_select)){
$color[] = $row['colors'];
$votes[] = $second_row['votes'];
echo "<tr><td>$color</td><td>$votes</td></tr>";
}
Short explanation:
It will fetch the select and store into an array (because what you were doing is selecting multiple rows into one single variable) and then just display with the echo.

Storing multiple rows from MySQL in separate variables

I am writing a web application in PHP which will store employee data and generate employee ID cards to PDF. I am using FPDF for creation of PDFs and that works fine. I am having a problem with showing results from MySQL database.
I have to generate PDF with 4 employee ID cards and I am not sure how to get them from the database. So far I am using LIMIT option in the query to get only 4 results and i will have an if statement based on mysql.php?id=1 id which will define the limit. It is a little messy but there are not going to be more than 80 employees.
This is my code:
$id = $_GET['id'];
if ($id == 1) {
$limit_start = 0;
$limit_end = 4;
}
$result=mysql_query("SELECT users.tajemnik, users.dateCreated, users.showmeID,
users.workerName, users.dateCreated, users.workerPlace, users.workerSID, uploads.userID, uploads.data, uploads.filetype
FROM users INNER JOIN uploads ON users.showmeID = uploads.userID ORDER BY workerName DESC LIMIT $limit_start, $limit_end") or die (mysql_error());
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
while($row = mysql_fetch_array($result)){
$workerName = $row["workerName"];
$workerPlace = $row["workerPlace"];
$workerSID = $row["workerSID"];
$tajemnik = $row["tajemnik"];
$showmeID = $row["showmeID"];
$mysqldatetime = strtotime($row['dateCreated']);
$image = $row["data"];
$phpdatetime = date("d.m.Y",$mysqldatetime);
}
This will get me the first result from the query. I need to get information from all 4 rows and have them stored in variables like $workerName1, $workerName2 etc. I hope it makes sense what I am trying to do.
Thank you for your replies!
V.
I need to get variables like $workerName1, $workerName2 etc
Nope, you don't.
You actually need an array.
So, first, get yourself a function
function sqlArr($sql){
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
if ($res) {
while($row = mysql_fetch_array($res)){
$ret[] = $row;
}
}
return $ret;
}
then write a code
mysql_query("SET NAMES 'utf8'") or die('Spojení se nezdařilo');
$sql = "SELECT users.tajemnik, users.dateCreated, users.showmeID, users.workerName,
users.dateCreated, users.workerPlace, users.workerSID, uploads.userID,
uploads.data, uploads.filetype
FROM users
INNER JOIN uploads ON users.showmeID = uploads.userID
ORDER BY workerName DESC LIMIT $limit_start, $limit_end";
$data = sqlArr($sql);
Now you have all your data in the $data array.
So, you can loop over it or access single values like
echo $data[0]['tajemnik'];
or
foreach($data as $row) {
//do whatever you want with database row
echo $row['tajemnik'];
}

Categories