Using mysqli and rand() - php

Trying to create a page where users can create a character with a base, one marking and eye colour. The three descriptions are all stored in seperate tables and are called randomly. I would like to limit the amount of times they are called so the user can't run through them all until finding a combo they like.
<?php
if(!isset($_SESSION['count']))
$_SESSION['count'] = 0;
if($_SESSION['count'] < 5) {
$_SESSION['count']++;
$query = $mysqli->query("SELECT `base` FROM `bases` WHERE `type` = 'Starter' ORDER BY rand()");
while($info = $query->fetch_assoc()) {
$_SESSION['refreshresultbase'] = $info['base'];
}
$querymark = $mysqli->query("SELECT `marking` FROM `markings` WHERE `type` = 'Starter' ORDER BY rand()");
while($infomark = $querymark->fetch_assoc()) {
$_SESSION['refreshresultmarking'] = $infomark['marking'];
}
$query3 = $mysqli->query("SELECT `colour` FROM `eyes` WHERE `type` = 'Starter' ORDER BY rand()");
while($infoeye = $query3->fetch_assoc()) {
$_SESSION['refreshresulteyes'] = $infoeye['colour'];
}
}
?>
Still really really new to mysqli so I apologise if this is a simple error.

Related

The first html row is not being displayed

So, let’s say I have 10 rows in my database. However, after the mysql query, only 9 rows are being displayed in the html table.
I need every row from the database to be displayed in the html table.
I hope someone can point me in the right direction. I’ll be here if I need to provide anymore details.
This is my code:
<?php
$sqlQuery = "SELECT * FROM periods";
$result = mysqli_query($conn, $sqlQuery);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$out = $row['fell_out'];
$in = $row['fell_in'];
$sum = $row['sum'];
$nextEstimate = $row['next_estimate'];
$nextEstimateDays = $row['next_estimate_days'];
$notes = $row['notes'];
$sqlQueryLastDate = "SELECT * FROM (select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultLastDate = mysqli_query($conn, $sqlQueryLastDate);
$resultCheckLastDate = mysqli_num_rows($resultLastDate);
if ($resultCheckLastDate > 0) {
while ($rowLastDate = mysqli_fetch_assoc($resultLastDate)) {
$lastInDate = $rowLastDate['fell_in'];
$sqlQueryCurrentDate = "SELECT * FROM (select * from periods WHERE id = $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
$resultCurrentDate = mysqli_query($conn, $sqlQueryCurrentDate);
$resultCheckCurrentDate = mysqli_num_rows($resultCurrentDate);
if ($resultCheckCurrentDate > 0) {
while ($rowCurrentDate = mysqli_fetch_assoc($resultCurrentDate)) {
$currentOutDate = $rowCurrentDate['fell_out'];
$lastIn = new DateTime($lastInDate);
$currentOut = new DateTime($currentOutDate);
$intervalLastCurrent = $lastIn->diff($currentOut);
$elapsedLastCurrent = $intervalLastCurrent->format('%a days %h hours');
/*Why? Php is erasing everything after adding the above variable to the table...Entire first row gets erased!*/
echo "
<tr>
<td>".$id."</td>
<td class='test'>".$elapsedLastCurrent."</td>
<td class='dateOutResult'>".$out."</td>
<td class='dateInResult'>".$in."</td>
<td class='sumHours'>".$sum."</td>
<td class='nextEstimate'>".$nextEstimate." (".$nextEstimateDays.")</td>
<td class='notes'>".$notes."</td>
</tr>";
} /*$sqlQueryCurrentDate*/
}
} /*$sqlQueryLastDate*/
}
} /*$sqlQuery*/
}
?>
Here's the live result: https://unidrones.co.za/periods
I am really new to mysql/php so I do not understand what I'm doing wrong. The nested queries is probably not the best approach to use, but I'm still learning, and any input will be deeply appreciated.
This is because your query is
//select * from periods WHERE id < $id ORDER BY id DESC LIMIT 1;
your first $id will be always equal id.

Get story and all its comments in 1 query

I am trying to create an PHP api in which I am trying to retrieve news storys and all its comments and send it as json.
Here is what i have so far:
$sql = "SELECT * FROM fb_clubnews WHERE clubid='$groupId' AND ori_newsid = 0 ORDER BY newsid DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$storId = $row["newsid"];
$commentArray = array();
$wallAray[] = array("author"=>$row["userid"],
"story"=>$row["news"],
"date"=>$row["date"],
"time"=>$row["time"],
"matchid"=>$row["fk_match_id"],
"comments"=>$commentsArray);
}
}
My issue is, that I would like to avoid creating a sql inside an sql and loop through it?! The second inside sql would be:
$sql = "SELECT * FROM fb_clubnews WHERE ori_newsid = $storId ORDER BY newsid DESC";
How do I get the $commentArray filled up with comments.
My DB Structure for fb_clubnews looks like this:
int newsid (autoincrement),
int userid,
text news,
int data,
int time,
int matchid,
int ori_newsid
Hoping for help on this and thanks in advance :-)
Something like this:
$sql = "SELECT *, A.newsid as main_news_id FROM fb_clubnews A LEFT JOIN fb_clubnews B ON B.ori_newsid = A.newsid WHERE A.clubid='$groupId' AND A.ori_newsid = 0 ORDER BY A.newsid DESC";
$result = $conn->query($sql);
$wallAray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$storId = $row["main_news_id"];
if(array_key_exists($storId, $wallAray)) {
$commentArray[] = $wallAray;
} else {
$wallAray[$storId] = array();
$commentArray = array();
}
$wallAray[] = array("author"=>$row["userid"],
"story"=>$row["news"],
"date"=>$row["date"],
"time"=>$row["time"],
"matchid"=>$row["fk_match_id"],
"comments"=>$commentsArray);
}
}

Predefined counter not updating in select statement

Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";

Multiple SQL If statements within PHP While loops

I've created a script to run on my database at five minute intervals as a cron job. It's not a well written piece of code, but it's done quickly and should do the job for now.
I'm executing a WHILE loop to execute multiple if statements which in turn have multiple SQL statements within them. Problem is, it's only iterating the WHILE loop once and then stops and i'm not entirely sure why. Code is as below:
<?php
require_once('config.php');
$hashtags = mysql_query("SELECT id, hashtag FROM hashtags WHERE enabled = '1'") or die(mysql_error());
while($row = mysql_fetch_array($hashtags))
{
$hashtag_id = $row['id'];
$hashtag = $row['hashtag'];
//Get id and latest_tweet_id from report log
$latest_report_tweet_id_query = mysql_query("SELECT id, latest_tweet_id FROM reports_log WHERE name = 'post_count' AND hashtag_id = '".$hashtag_id."' LIMIT 1") or die(mysql_error());
if (mysql_num_rows($latest_report_tweet_id_query) == 0) {
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
$post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$post_count = $post_count_query['tweet_count'];
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date("Y-m-d H:i:s")."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."'")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("INSERT INTO reports_log (timestamp, hashtag_id, name, latest_tweet_id, latest_report_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', 'post_count', '".$new_report_tweet_id."', '".$report_id."')"))
{
echo "Successfully created report! NEW";
}
else {
echo "Failed updating report log! NEW";
}
}
else
{
echo "Failed making report! NEW";
}
}
else {
//Set the latest report id
$latest_report_tweet_id_array = mysql_fetch_array($latest_report_tweet_id_query);
$latest_report_log_id = $latest_report_tweet_id_array['id'];
$latest_report_tweet_id = $latest_report_tweet_id_array['latest_tweet_id'];
//Query to get the latest tweet_id in the database
$new_report_tweet_id_query = mysql_fetch_array(mysql_query("SELECT tweet_id FROM tweet_tags WHERE tag = '".$hashtag."' ORDER by tweet_id desc LIMIT 1")) or die(mysql_error());
$new_report_tweet_id = $new_report_tweet_id_query['tweet_id'];
//Query to get the new post count from database
$new_post_count_query = mysql_fetch_array(mysql_query("SELECT count(tweet_id) as tweet_count FROM tweet_tags WHERE tag = '".$hashtag."' AND tweet_id > '".$latest_report_tweet_id."' AND tweet_id <= '".$new_report_tweet_id."'")) or die(mysql_error());
$new_post_count = $new_post_count_query['tweet_count'];
$old_post_count_query = mysql_fetch_array(mysql_query("SELECT id, post_count FROM post_count_reports ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$old_post_count = $old_post_count_query['post_count'];
$post_count = $old_post_count + $new_post_count;
if(mysql_query("INSERT INTO post_count_reports (timestamp, hashtag_id, post_count, latest_tweet_id) VALUES ('".date('Y-m-d H:i:s')."', '".$hashtag_id."', '".$post_count."', '".$new_report_tweet_id."')"))
{
//Get just created id of the report
$report_id_query = mysql_fetch_array(mysql_query("SELECT id FROM post_count_reports WHERE hashtag_id = '".$hashtag_id."' AND latest_tweet_id = '".$new_report_tweet_id."' ORDER by timestamp desc LIMIT 1")) or die(mysql_error());
$report_id = $report_id_query['id'];
if(mysql_query("UPDATE reports_log SET id = '".$latest_report_log_id."', timestamp = '".date('Y-m-d H:i:s')."', latest_tweet_id = '".$new_report_tweet_id."', latest_report_id = '".$report_id."' WHERE name = 'post_count'"))
{
echo "Successfully created report!";
}
else {
echo "Failed updating report log!";
}
}
else
{
echo "Failed making report!";
}
}
}
?>
Massive error on my part, turns out whilst there were three hashtags in the hashtags table there were only rows with one of the hashtags in the tweet_tags table. Wasted a few hours on this one.
Moral of the story, always log and check for errors!

Creating arrays from Mysql queries inside a foreach loop

I am trying to populate a table displaying statistics. I have a list of campaign id's have been placed into an array using the following query:
$query = "SELECT `id` FROM `c_templates` ORDER BY `id`";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id[] = $row['id'];
}
Once I have all of my id's, I am using a foreach loop to make 5 queries per id gathering all the table data.
foreach($id as $i){
// sent
$query = "SELECT `template`, COUNT(*) as count FROM `s_log` WHERE `template` = '".$i."' AND `time_sent` BETWEEN '".$start."' AND '".$stop."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$template[] = $row['template'];
$count[] = $row['count'];
}
// opens
$query = "SELECT COUNT(*) as count FROM `t_opens` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$opens[] = $row['count'];
}
// clicks
$query = "SELECT `campaign_id`, COUNT(*) as count FROM `t_analytics` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$click_count[] = $row['count'];
}
// conversions
$query = "SELECT `conversion_value`, COUNT(*) as count FROM `t_analytics` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."' AND `conversion_value` > 0";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$conversion_value[] = $row['conversion_value'];
$conversion_count[] = $row['count'];
}
// bounce rate
$query = "SELECT COUNT(*) AS `ck` FROM `s_log` WHERE `time_sent` BETWEEN '".$start."' AND '".$stop."' AND `status` = 'hardbounce' OR `status` = 'softbounce' AND `template` = '".$i."'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$bounce_count[] = $row['ck'];
}
}
The issue is that this process takes 4-5 seconds to perform over 40-50 id records. I placed some timers after each query to confirm the queries were performing correctly and they were. I ran OPTIMIZE and double checked to be sure everything was properly indexed. As far as I can tell, the issue is not in mysql.
The only thing I could find is that there is a .1-.5 second delay after each loop cycle. When trying to run 40-50 rows, this definitely begins to add up.
My question: Is there a better and faster way to fetch this data? Is there something else I should be checking to speed the process up?
The only solution I could think of was to run one query for each statistic (5 total queries) fetching the data for all id and placing them in a array for later display. I'm not sure how that could be done or if it's even possible. It seems to me I would have to run a separate query for each id, but I'm hoping I'm wrong.
Any help will be greatly appreciated!!

Categories