How to find what random row from a random table was chosen - php

I'm trying to create a website where users can vote on different items from a game, like a tierlist. I want the item that a user votes on to be from a random table and a random row in that table.
Right now, I have the following code set up to find the random item:
$ran = mt_rand(1, 10);
switch ($ran) {
case "1":$sql = "SELECT item, rating FROM ditems ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["gun"];
};
break;
case "2":$sql = "SELECT item, rating FROM citems ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["item"];
};
etc
The problem I run into is that I can't access what the chosen item is outside of the switch{} statement because the $row array is declared locally, but I have to be able to do that so that I can seet up a button to vote on the item.
EDIT: I decided to throw all items in a single table and pick a item using
ORDER BY RAND LIMIT 1

You can SELECT another column with a text constant to denote what entity is selected:
$ran = mt_rand(1, 10);
switch ($ran) {
case "1":$sql = "SELECT 'ditem' as entity, item, rating FROM ditems ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["gun"];
};
break;
case "2":$sql = "SELECT 'citem' as entity, item, rating FROM citems ORDER BY RAND() LIMIT 1";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["item"];
};
etc

Related

How can i generate a unique incremental id like an invoice number (PHP)

Please how can I generate a unique id that increments when a new invoice is created.
For example, I have an invoice with the id NR20200001 so the Next invoice created the Id should be NR20200002.
This is my code below, I can't seem to increment the unique id I generated, so I just generated it randomly, but I need to generate it incrementally
<?php
$qry = "SELECT * from requisitions order by req_id desc";
$result = mysqli_query($connection, $qry);
$row = mysqli_fetch_array($result);
$lastid = $row['req_id'];
if($lastid == ""){
$number = "NR".date("Y").date("s");
}
else{
$length=2;
$number = substr($lastid,4);
$number = intval($number);
$number = "NR".date("Y").date("s").substr(str_shuffle(str_repeat($x='0123456789',ceil($length/strlen($x)))),1,$length);
}
?>
Firstly, you should set req_id to primary key and auto increment on database
Secondly, add LIMIT 1 for get only the latest req_id:
$qry = "SELECT * from requisitions order by req_id desc LIMIT 1";
Next, change condition follow as below:
<?php
$qry = "SELECT * from requisitions order by req_id desc LIMIT 1";
$result = mysqli_query($connection, $qry);
$row = mysqli_fetch_array($result);
if($row['req_id'] == "" || $row['req_id'] == null)
{
$lastid = 0;
}
else
{
$lastid = $row['req_id'];
}
$nextid = sprintf("%04d", $lastid+1); //set to 4 digit
$number = "NR".date("Y").$nextid;
?>
Note: Do not delete record from table because it will make duplicate invoice number. You should add field flag for active/inactive.
Please check code for increment number
6) ? $lastid : substr('00000000' . $lastid, -6);
$getValue = "NR".date("Y").date("s").$getValue;
}
?>

How to display multiple fetched data?

I am using the following to fetch the latest articles from the database:
//Latest Article
$title_query1 = "SELECT title FROM articles ORDER BY id DESC LIMIT 1";
$description_query1 = "SELECT description FROM articles ORDER BY id DESC LIMIT 1";
$content_query1 = "SELECT content FROM articles ORDER BY id DESC LIMIT 1";
$image_query1 = "SELECT image FROM articles ORDER BY id DESC LIMIT 1";
$title_result1 = mysqli_query($con, $title_query1) or die(mysqli_error($con));
$description_result1 = mysqli_query($con, $description_query1) or die(mysqli_error($con));
$content_result1 = mysqli_query($con, $content_query1) or die(mysqli_error($con));
$image_result1 = mysqli_query($con, $image_query1) or die(mysqli_error($con));
//Second Latest Article
$title_query2 = "SELECT title FROM articles ORDER BY id DESC LIMIT 2,1";
$description_query2 = "SELECT description FROM articles ORDER BY id DESC LIMIT 2,1";
$content_query2 = "SELECT content FROM articles ORDER BY id DESC LIMIT 2,1";
$image_query2 = "SELECT image FROM articles ORDER BY id DESC LIMIT 2,1";
$title_result2 = mysqli_query($con, $title_query2) or die(mysqli_error($con));
$description_result2 = mysqli_query($con, $description_query2) or die(mysqli_error($con));
$content_result2 = mysqli_query($con, $content_query2) or die(mysqli_error($con));
$image_result2 = mysqli_query($con, $image_query2) or die(mysqli_error($con));
However, i'm not sure how I can then do something like this:
<h1>Here is the first article: <?php $title_result1 ?><h1>
<h2>Here is the first article description: <?php $description_result1 ?>
<h1>Here is the second article: <?php $title_result2 ?><h1>
<h2>Here is the second article description: <?php $description_result2 ?>
Also, is this method not good? If I am going to do this for 100+ articles, will it cause the web page to load slowly?
Thanks
You do not need to do a single query for each column. You can get all columns for a row by doing select * Also, as mentioned, you can fetch as many rows as you want, and loop through them.
I prefer the while method.. Example, show last 100 articles
// fetch latest 100
$sql = "SELECT * FROM articles ORDER BY id DESC LIMIT 100";
if ($result = mysqli_query($con, $sql)){
// got results, convert result object to array called $row
while ($row = mysqli_fetch_array($result)) {
// echo out $row array elements with
//the column names from the database as array index
echo '<h2>'. $row['title'] .'</h2>'; // example wrap results with HTML
echo '<b>' .$row['description'] .'</b>';
echo $row['content'];
echo <img src="'. $row['image'] .'" title="'.$row['description'].'">';
echo '<br>'; //so next result is on new line
} // end of while loop
} else {
//no result, error
}

Getting exact value from fetched array from MySql

Not a duplicate of Select specific value from a fetched array
I have a MySql database as:
Here's my query:
$sql = "SELECT * FROM data ORDER BY Score DESC";
I want it to be a leaderboard which people can update their scores so I can't use
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
I want to get Username of the second row in my query.So I wrote:
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
}
echo "Result = '".$row[1]['Username']."''";
}
?>
But it returns Result = '' like there's nothing in the array.
But if I write
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Name = '".$row['Username']."''";
}
}
It will return : Parham, Mojtaba, Gomnam, Masoud,
So what am I doing wrong in the first snippet?
You can not access $row outside of while loop.
So store result in one new array, and then you can access that new array outside the while loop:
$newResult = array();
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$newResult[] = $row;
}
}
echo "Result = '".$newResult[1]['Username']."''"; // thus you can access second name from array
Because you write where condition after ORDER by at
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
The sequence of query is
SELECT * FROM data // select first
WHERE ID = 1
ORDER BY Score DESC// Order by at last
Check http://dev.mysql.com/doc/refman/5.7/en/select.html
And for second case you need to fetch Username inside while loop and use $row['Username'] instead $row[1]['Username']
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Result = '".$row['Username']."''";// write inside while loop
}
You can assign row value to any array and use that array.
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $row;
}
echo "Result = '".$rows[1]['Username']."'";
}
?>
Or if you want only second highest score from column you can user limit as
$sql = "SELECT * FROM data ORDER BY Score limit 1,1";

Echo the 2 last columns of tabel

I have a table and i want to echo the 2 last rows of my tabel, I used the below code but just the last one showed, what is the problem.
$result1 =(mysql_fetch_array(mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")));
Print $result1['time'];
mysql_fetch_array = 1 fetch.
do it again for fetching 2nd result.
Also, use mysqli eh.
You're doing mysql_fetch_array only one time, so it gets the first element. If you want to get all the elements, then do it again, or use a loop.
Something like:
$query = "SELECT * FROM $table ORDER BY id DESC LIMIT 2";
while($row = mysql_fetch_array(mysql_query($query) )
{
echo $row['time'].'<br>';
}
For 2 Or more rows you need to loop it
$sql = mysql_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2")
while($row=mysql_fetch_array($sql))
{
echo $row['time']."<br>";
}
$query = mysqli_query("SELECT * FROM $table ORDER BY id DESC LIMIT 2");
while ($result = mysqli_fetch_array($query)) {
echo $result['time'];
}
Gives out every return of your database (2 in this case). You should use mysqli_-functions.
Maybe you should try like this, since mysql_fetch_array returns only one row
while ($row = mysql_fetch_array($yourQuery)) {
echo $row["yourAlias"];
}
Further details here : http://fr2.php.net/manual/en/function.mysql-fetch-array.php
My solution:
$limit = 2;
$sql = "SELECT * FROM $table ORDER BY id DESC LIMIT $limit";
$result = mysql_query($sql);
$array = array(); $i = 0;
while($row = mysqli_fetch_array($result))
{
$array[$i] = $row;
$i++;
}
var_dump($array[0]);
var_dump($array[1]);

MySQL query within another query's while loop in PHP

I have the following code:
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
extract($result);
if ($activity_type == "discussion") {
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($result = mysql_fetch_array($query)) {
extract($result);
echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
}
} elseif ($activity_type == "file") {
}
}
But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.
Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...
$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
and
$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
same with $results var...
I would suggest you change to $query and $query2 but best to use something like
$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {
and
$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {
I would also avoid using extract - as you might be overwriting vars your not expecting to...
You have to create another connection to the database so that you can run them at the same time.
OR
You can load the results of the first one into an array, and then just loop through the array.

Categories