Issues getting PHP shuffle to output results - php

I'm attempting to shuffle the users that I have in my database and then output the first and last name of those results. I have PHP error coding in this file and it is not throwing any errors. Just nothing is outputting not even..
if ($shuffle_firstname == true) {
echo $shuffle_firstname . $shuffle_lastname;
} else {
echo "No users have been registered yet.";
}
Does anyone see what I'm doing wrong?
$con = mysqli_connect("localhost", "root", "", "db");
$shuffle_run = mysqli_query($con,"SELECT * FROM users WHERE `group`= 3");
$shuffle_numrows = mysqli_num_rows($shuffle_run);
if( $shuffle_numrows > 0) {
while($shuffle_row = mysqli_fetch_assoc($shuffle_run)){
$shuffle_id = $shuffle_row['id'];
$shuffle_firstname = $suffle_row['firstname'];
$shuffle_lastname = $shuffle_row['lastname'];
$shuffle_username = $shuffle_row['username'];
$shuffle_email = $shuffle_row['email'];
if ($shuffle_firstname == true) {
echo $shuffle_firstname . $shuffle_lastname;
} else {
echo "No users have been registered yet.";
}
}
}
if(isset($_POST['shuffle'])) {
$shuffle_row = array();
shuffle($shuffle_row);
foreach ($shuffle_row as $shuffle) {
echo $shuffle_firstname . " " . $shuffle_lastname;
}
}
?>
<input type="submit" value="Shuffle" name="shuffle">

You are overwriting your results with an empty array, then you use shuffle on an empty array, then you're looping the empty array using foreach. I've cleaned up the code, could you try this?
<?php
$con = mysqli_connect("localhost", "root", "", "db");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Normal results: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
if (isset($_POST['shuffle'])) {
shuffle($array);
echo 'Shuffled results: <br>';
foreach ($array as $result) {
echo $result['firstname'] . ' ' . $result['lastname'] . '<br>';
}
// echo $results[0]['firstname'] . ' ' . $results[0]['lastname']; // To display one random result
}
?>
<form method="post">
<input type="submit" value="Shuffle" name="shuffle">
</form>

Related

Variables inside while loop

I have following code, I try to style output with CSS, but I have small problem, my code show all database entries, which is OK, but when I remove comment from WHILE loop, and comment echo, its showing only first row of entries from database.how can I do same thing and show multiple results from database by use variables in While Loop?:
<?php
error_reporting(0);
require 'connect.php';
$search = $_POST['search'];
//$checkout = $_POST['checkout'];
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM area where destination='{$search}'";
$result = mysqli_query($conn, $sql);
if($count = $result->num_rows) {
echo '<p>', $count, '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'],' ',$row['place'], $row['tosee'], '<br>';
/$destination =$row["destination"];
//$place =$row["place"];
/$destination =$row["destination"];
//$place =$row["place"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
and inside my HTML file:
location: <?php echo $destination; ?>
places: <?php echo $place ; ?>
views: <?php echo $tosee; ?>
Do this...
$out .= $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
Then you can use the $out variable anywhere else...
Even for these...
$destination .= $row["destination"];
$place .= $row["place"];
Since well....are in the while loop
I found a few small errors, you had a ',' instead of a '.' to concatenate a variable.
if($count = $result->num_rows) {
echo '<p>' . $count . '</p><br><br>';
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row['destination'].' '.$row['place'].' '.$row['tosee']. '<br>';
//$destination =$row["destination"];
//$place =$row["place"];
//$destination =$row["destination"];
//$place =$row["place"];
}
}
and for php comments it is: //

Get function is not working , passes empty to the another page

Well i use this form of
add.php
echo " <td><form action='view_ticket.php' method='get'>
<input type='hidden' id='itemid' name='itemid' value='". $row["id"] ."'/>
<input type='submit' value='Buy' class='btn-link'/>
</form></td>";
echo "</tr>";
And i got this
view_ticket.php
<?php
session_start();
$conn = mysqli_connect("localhost", "localhost", "localhost",
"localhost");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['itemid'];
$sql = "SELECT id,username FROM tickets WHERE id = '" . $id . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row['username'] = $_SESSION['username']) {
}
else
{
header("location:/quickshops/buyer/tickets.php");
}
}
}
?>
the only problem i guess that $id = $_GET['itemid']; gets out empty idk how
I checked the source code of add.php , the ids in hidden area are real ,true, and numbers
Output $_GET at each step to see where you loose it, for instance
echo 'About to look for id "' . htmlspecialchars($id) . '"<br>';
$result = $conn->query($sql);
echo 'Just executed SQL query<br>';
var_dump($_GET); echo '<br>';
if ($result === false) {
echo 'SQL Query Error!<br>';
var_dump($_GET); echo '<br>';
} else if ($result->num_rows > 0) {
echo $result->num_rows . ' row(s) found<br>';
var_dump($_GET); echo '<br>'; /* do something */
} else {
echo 'No rows round<br>';
var_dump($_GET); echo '<br>';
}

How to fetch main, sub and child categories from three tables. PHP MYSQLI

i am working on a project, in which i want to use Categories and their Sub and Child categories, i've created 3 tables ( MainCats, SubCats, ChildCats ).
now i want to fetch data from those tables and want to store in option of HTML.
Here is code PHP, MYSQLI and HTML code.
$cat_fetch = "SELECT categories, sub_categories, child_categories FROM categories.maincatSd, sub_categories.subcat_name, child_categories.child_cat_name";
$cat_run = mysqli_query($con, $cat_fetch);
echo "<option value='' >ڪيٽيگري چونڊيو</option>";
if(mysqli_num_rows($cat_run) >0){
while($cat_row = mysqli_fetch_array($cat_run)){
$cat_name = $cat_row['child_cat_name'];
$cat_name = $cat_row['subcat_name'];
$cat_name = $cat_row['maincatSd'];
//$cat_name = $cat_row['subcat_name'];
echo "<option value='".$cat_name."' ".((isset($Catagory) and $Catagory == $cat_name)?"selected":"")." >".ucfirst($cat_name)."</option>";
}
}else{
echo "<option name='Catagory' tabindex='2' id='Catagory' value=''>NoCat</option>";
}
From the output of your given image.. I don't feel you need to maintain any kind of relation at the time of fetching records from tables. It just needs to fetch records from those three tables & build the options list & print show on the web page. If that's exactly what you want, then check out this.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// Connect to DB
$mysqli = new mysqli('127.0.0.1', 'host', 'password', 'DB_Name');
if ($mysqli->connect_errno) {
echo "Error: Failed to make a MySQL connection, here is why: \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
echo "Error: " . $mysqli->connect_error . "\n";
exit;
}
// ---Fetch all main category records---
$sql = "SELECT * FROM main_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsMainCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsMainCat[] = $dataSource;
}
}
// ---Fetch all Sub category records---
$sql = "SELECT * FROM sub_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsSubCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsSubCat[] = $dataSource;
}
}
// ---Fetch all Child category records---
$sql = "SELECT * FROM child_cat";
if (!$result = $mysqli->query($sql)) {
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
$totRecordsChildCat= array();
if($result->num_rows){
while($dataSource = $result->fetch_assoc()){
$totRecordsChildCat[] = $dataSource;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
echo "<select>";
echo "<option value=''>Select Category</option>";
foreach ($totRecordsMainCat as $key => $value)
{
$cat_name = $value['cat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsSubCat as $key => $value)
{
$cat_name = $value['subcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
foreach ($totRecordsChildCat as $key => $value)
{
$cat_name = $value['childcat_name'];
echo "<option value='$cat_name'>$cat_name</option>";
}
echo "</select>";
?>
</body>
</html>
Why not do it using 3 different queries and nested loops..
SELECT * FROM main_cat
// Loop query result
SELECT * FROM sub_cat WHERE sub_cat_id = main_cat_id
// Loop query result
SELECT * FROM child_cat WHERE child_cat_id = sub_cat_id
// Loop query results

For each results- Mysql - JSON

How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.

Mixing html with php search results?

I am trying to make the different the different rows have line breaks but its not working.
How is this done!? Please check my code below
Thanks guys!
James
<?php
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '$search%' AND lastname LIKE '$searchterm'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
}
mysql_free_result($result);
?>
<?php echo $row["name"];?>
<br>
<?php echo $row["lastname"];?>
<br>
<?php echo $row["email"];?>
Beats me what you find so hard about it:
while ($row = mysql_fetch_array(...)) {
echo ...
echo '<br>';
}

Categories