Data from mysql is not getting retrieved on every page refresh - php

Iam trying to fetch the random data from mysql database, but it only fetches the same row on page refresh
I tried to run the query to get the random single row data from mysql and display on the webpage using php, but it only retrieving only the same row every time
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1
<?php
$link = mysqli_connect("host", "username", "password", "db_name");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND() LIMIT 1";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>email_md5</th>";
echo "<th>age_group </th>";
echo "<th>age</th>";
echo "<th>income</th>";
echo "<th>Income_group </th>";
echo "<th>gender</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['email_md5'] . "</td>";
echo "<td>" . $row['age_group'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['income'] . "</td>";
echo "<td>" . $row['Income_group'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
I need the random row data to be displayed everytime the page is refreshed. Will really be helpful if anyone can suggest be the best solution.

$sql = "SELECT * FROM identity_explorer_demographics ORDER BY RAND()
LIMIT 1";
Change the line to
$randomv=rand(min,max);
$sql = "SELECT * FROM identity_explorer_demographics ORDER BY $randomv
LIMIT 1";
Here is my implementation in another case where I have to choose from a random id available - Yii 2 Framework
$prodcutids= \app\models\TblProduct::find()->all();
$targetproduct= ArrayHelper::map($prodcutids, 'id','id');
$productdetails= \app\models\TblProduct::findOne(['id'=>array_rand($targetproduct)]);
$productseriesname= \app\models\TblSeries::findOne(['id'=>$productdetails['Serie']]);
Or if you have an id column
$sql = "SELECT * FROM identity_explorer_demographics WHERE id=$randomv
LIMIT 1";
rand(min,max)
min specifies the lowest value that will be returned.
max specifies the highest value to be returned.

You mix it with PHP
$sql = 'SELECT * FROM `identity_explorer_demographics`';
//Perform query and parse result, E.G $sql = db::query($sql);
function getRandomRow($sql) {
$random_row = count(0, count($sql));
foreach($sql as $row => $result) {
if ($row == $random_row) {
return $row;
}
}
}

Related

How to use MySQL query results as options in HTML forms

<?php
$con = new mysqli('localhost', 'root' ,'', 'world');
$query = 'SELECT * FROM city ORDER BY Name';
if ($result = mysqli_query($con, $query)) {
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>"
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['CountryCode'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
}
mysqli_close($con);
?>
This simple code will display every entries in this database. Now I would like to add a selective display option by choosing the CountryCode.
$query2 = 'SELECT DISTINCT CountryCode FROM city ORDER BY CountryCode';
How do I use the result I got from the query above and make it become radio buttons to choose what to display?
Similar to what you are doing already: Something like
while ($row = mysqli_fetch_assoc($result)) {
echo "<input type='radio' name='whatever' value='".$row['Name']."'>". $row['Name'];
}
Ofcourse the field names can be whatever you like them to be, as long as you select them in the query

select SQL table from php variable

I have selected a random table from a list/array and I want to be able to call this random table with the mysqli_query function i.e. select a table dynamically
Here is my code:
<?php
$mysqli=mysqli_connect(HOST,USERNAME,PASSWORD,DATABASE);
// Check connection
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Looks at all prodcuts and selects those that have special offers enabled
// Selects a random table from the array
$tables_special = ["ajbs_products_console" ,"ajbs_products_console_games", "ajbs_products_pc", "ajbs_products_pc_games", "ajbs_products_pc_parts"];
$rtable = $tables_special[floor (rand(0,count($tables_special)-1))];
echo "<p>".$rtable." was selected</p>";
$products = mysqli_query("SELECT * FROM '".$rtable."'");
echo "<p>".$products."</p>";
while($productRow = mysqli_fetch_array($products))
{
if ($productRow['product_specials'] == 1)
{
echo "<table>";
echo "<tr>";
echo "<td rowspan='2'><img src=" . $productRow['product_image'] . "/></td>";
echo "</tr>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>Product Name</td>";
echo "<td>" . $productRow['product_name'] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Description</td>";
echo "<td>" . $productRow['product_description'] . "</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($mysqli);
?>
Im at a loss of why this is not working
Thanks,
Bull
You should not quote table names with single quotes but with backticks, single quotes makes it a string instead of a table name;
Also, the function mysqli_query takes an extra parameter, the connection.
$products = mysqli_query("SELECT * FROM '".$rtable."'");
should be;
$products = mysqli_query($mysqli, "SELECT * FROM `".$rtable."`");
Try
$products = mysqli_query($mysqli, "SELECT * FROM ".$rtable);

Sort and Pagination combined, PHP with SQL

I've got a CV database, you can see the fields below and they are pretty standard. Retrieval is done by a simple form sending the information into an SQL database.
I was happy with my simple system till I was flooded with over 500 applicants in my inbox. My previous system allowed me to view the applicants only one by one which would have taken forever...
What I'm trying to achieve is a simple backend page similar to the phpmyadmin of the table view. (no i don't want to just use phpmyadmin as i'd like to give the CV sifting task to other employees)
Basically the concept is to display the table like an excel, allow sorting by clicking on headers, pagination [20 rows per page] and a check box to delete row.
I'm ok with asking for some help as I have put alot of effort into trying to figure this out ;)
So far what i've got is:
The sorting works no problem, clicking on one of the headers spits out localhost/mena/new3.php?sort=fname to the address bar and parses the correct Sql query and sorts the page.
The pagination so far does not work. The page displays all 815 candidates. It is providing the numbered links 1-42 that when clicked on result in the address bar changing to localhost/new3.php?page=2 but 0 change.
Also for the life of me i can't see how to include the php delete into this..
9 yo pseudo code idea of it is :
//Input the rows from SQL
While($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $checkbox1
if checkbox1=true then mysqli_query($con,"DELETE FROM cv WHERE .$row[].");
echo "<td>" . $row['title'] .
My code so far:
<?php
$con=mysqli_connect("localhost","root","","test_db-jil");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Pagination
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 20;
// Sort, from headers.
if(isset($_REQUEST['sort'])){
if($_GET['sort'] == "title"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY title");
}
elseif($_GET['sort'] == "fname"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY fname");
}
elseif($_GET['sort'] == "lname"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY lname");
}
elseif($_GET['sort'] == "gender"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY gender");
}
elseif($_GET['sort'] == "dob"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY dob");
}
elseif($_GET['sort'] == "nationality"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY nationality");
}
elseif($_GET['sort'] == "language"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY language");
}
elseif($_GET['sort'] == "phone"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY phone");
}
elseif($_GET['sort'] == "email"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY email");
}
elseif($_GET['sort'] == "uni"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY uni");
}
elseif($_GET['sort'] == "prog"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY prog");
}
elseif($_GET['sort'] == "graddate"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY graddate");
}
elseif($_GET['sort'] == "startdate"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY startdate");
}
elseif($_GET['sort'] == "grad"){
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY grad");
}
else{
$result = mysqli_query($con,"SELECT * FROM cv ORDER BY fname");
}
}
else{ // Default if no parameters passed
$result = mysqli_query($con,"SELECT * FROM cv");
}
//Table of Content
echo "<table border='1'>
<tr>
<th><a href=new3.php?sort=title>Title</a></th>
<th><a href=new3.php?sort=fname>First Name</a></th>
<th><a href=new3.php?sort=lname>Last Name</a></th>
<th><a href=new3.php?sort=gender>Gender</a></th>
<th><a href=new3.php?sort=dob>Date Of Birth</a></th>
<th><a href=new3.php?sort=nationality>Nationality</a></th>
<th><a href=new3.php?sort=language>Language</a></th>
<th><a href=new3.php?sort=phone>Phone No</a></th>
<th><a href=new3.php?sort=email>Email</a></th>
<th><a href=new3.php?sort=uni>University</a></th>
<th><a href=new3.php?sort=prog>Program</a></th>
<th><a href=new3.php?sort=graddate>Graduated</a></th>
<th><a href=new3.php?sort=startdate>Start Date</a></th>
<th><a href=new3.php?sort=grad>Applying for</a></th>
<th>CV File</th>
</tr>";
//Input the rows from SQL
While($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['gender'] . "</td>";
echo "<td>" . $row['dob'] . "</td>";
echo "<td>" . $row['nationality'] . "</td>";
echo "<td>" . $row['language'] . "</td>";
echo "<td>" . $row['phone'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['uni'] . "</td>";
echo "<td>" . $row['prog'] . "</td>";
echo "<td>" . $row['graddate'] . "</td>";
echo "<td>" . $row['startdate'] . "</td>";
echo "<td>" . $row['grad'] . "</td>";
echo "<td>" . $row['cvfilename'] ."</td>";
echo "</tr>";
}
echo "</table>";
//Get total count of rows then ceil divide by 20 as pages
$sql = "SELECT COUNT(*) as 'num' FROM cv";
$total_pages = $con->query($sql) or die(mysqli_error($connection));
$row = $total_pages->fetch_assoc();
$total_pages = ceil($row['num'] / 20);
for ($i=1; $i<=$total_pages; $i++) {
//Can I ?page= and ?sort= ??????
echo "<a href='new3.php?page=".$i."'>".$i."</a> ";
};
mysqli_close($con);
?>
Recap, please help me fix pagination, have it work with sort and finally add a delete check box to each row. :)
You know you can optimize that entire block of "else if" statements by just assigning the
$_GET to a variable:
$type = $_GET;
Then use that in your mysqli:
$result = mysqli_query($con, "SELECT * FROM cv ORDER BY $type");
To limit your results use LIMIT:
$result = mysqli_query($con, "SELECT * FROM cv ORDER BY $type LIMIT 20, $page");
20 = how many to return
$page = where you want the results to start from

Printing two separate SQL table data on the dynamically populated table - PHP

Can someone please help me on the following code? Simply put, I'm trying to get two separate SQL tables' data, one on the horizontal side (brands) and the other (distributors) on the vertical side of a dynamically populated table.
my issue is, if you go through the code I cant get the text boxes populated under each respective brand name I get to display from the database. The text boxes are appearing only for the first brand name column.
My second issue if how do I assign a unique ID or a name to a dynamically populated text box here?
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$sqlq="SELECT * FROM brands";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
$resultq = mysqli_query($db,$sqlq) or die ("SQL Error_er2");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
while($rowq = mysqli_fetch_array($resultq))
{
echo "<td>" . $rowq['bname'] . "</td>";
}
"</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='txt1'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
You're creating loop without relating to eachother, and the same goes for the execution of the querys...
If you want to solve it you will have to nestle the loops together, something like:
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
//Go through all distributors
while($rowq = mysqli_fetch_array($result)) {
echo "<td>" . $rowq['bname'] . "</td>";
//Show all brands for current distributor
$sqlq="SELECT * FROM brands where distributor_id = " . $rowq['rsm'];
$resultBrands = mysqli_query($db,$sql) or die ("SQL Error Brands");
while($row = mysqli_fetch_array($resultBrands))
{
$id = $row['rsm'];
echo "<tr>";
echo "<td>" . $row['dname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
//End show all brands for current distributor
}
//End Go through all distributors
A better solution though, would be something like (of course $q has to validated before input inside of query and also binded with bind_param()).
<?php
$q=$_GET["q"];
include ("../connection/index.php");
$sql = " SELECT * FROM distributors d";
$sql .=" LEFT JOIN brands b ON (d.brand_id = b.brand_id)";
$sql .=" WHERE d.rsm=$q";
$result = mysqli_query($db,$sql) or die ("SQL Error");
echo "<table border='1'>";
while($rowq = mysqli_fetch_array($result))
{
$id = rowq['rsm'];
echo "<tr>";
echo "<td>" . $rowq['dname'] . "</td>";
echo "<td>" . $rowq['bname'] . "</td>";
echo "<td><input type='text' name='textBox[]'></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($db);
?>
Take notice of the name='textBox[]'. From PHP you can access the variable with $_POST['textBox'] (or $_GET['textBox'] and PHP will return an array).

How to order by higher id sql

I have rows in MYSQL.
They are basically articles and rumours based on user input. In my query, i would like the table created to have the later results ranked higher. How would that Order By Query work?
$query = "SELECT * FROM rumours";
$query.= "ORDER BY"
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$band = $row['band'];
$title = $row['Title'];
$description = $row['description'];
echo "<table border='1'>";
echo "<tr>";
echo "<td> $title </td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'> $description </td>";
echo "</tr>";
echo "</table>";
}
Few things regarding your snippet.
Use a column list and avoid selecting *
mysql_ functions are being deprecated. You should use either mysqli_ or PDO functions.
You can save yourself time by calling your columns directly, rather than reassigning them variables.
When you are asking for the older records to display first, what is the criteria for this? Does a higher id mean the record is newer? I've assumed this in my answer.
Here's an improved version of your code using mysqli_:
$link = mysqli_connect("localhost", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$q = "SELECT id, band, Title, description FROM rumours ORDER BY id DESC";
$result = mysqli_query($link, $q);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "<table border='1'>";
echo "<tr>";
echo "<td>" . $row[id] . "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'>" . $row[description] . "</td>";
echo "</tr>";
echo "</table>";
}
mysqli_free_result($result);

Categories