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);
Related
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;
}
}
}
I know this involves a loop. I've done a number of searches but can't quite figure it out.
I'm using the following code to output the data with 3 items per row. What I'd really like to figure out how to do is to have them go ascending by column instead of by row, but dynamically depending on the number of records in the query, instead of defining the number of rows in the column.
<?php
define('DB_SERVER', "xxx");
define('DB_USER', "xxx");
define('DB_PASSWORD', "xxx");
define('DB_TABLE', "xxx");
$row_count = 0;
// The procedural way
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_TABLE);
$mysqli->set_charset("utf8");
$mysqli->query("SET NAMES 'utf8'");
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
$query = "
SELECT lvm.luchtvaartmaatschappij, COUNT(*) AS CountLVMPhotos
FROM tbl_photos p
LEFT JOIN tbl_luchtvaartmaatschappij lvm
ON p.img_lvm = lvm.IATACode
WHERE p.img_creator IN ('Daniƫl E. Cronk','Daniel E. Cronk')
GROUP BY lvm.luchtvaartmaatschappij
ORDER BY lvm.luchtvaartmaatschappij ASC ";
$result = mysqli_query($mysqli, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);
echo "
<table id='fotosBij' class='tablesorter-dropbox table-responsive ui-table-reflow'>";
echo "<tbody>";
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$items_in_row = 3 ;
$index = 0 ;
echo '<tr >';
while($row = mysqli_fetch_assoc($result)){
$index++ ;
echo "<td width='250px' valign='top'>" . $row['luchtvaartmaatschappij'] . "</td>";
echo "<td width='50px' valign='top'>" . $row['CountLVMPhotos'] . "</td>";
echo "<td width='80px'> </td>";
if ($index%$items_in_row == 0){
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
}
}
mysqli_close($mysqli);
?>
If I understand what you want correctly, this will do it:
if($result) {
$row1html = "<tr>";
$row2html = "<tr>";
while($row = mysqli_fetch_assoc($result)) {
$row1html .= "<td width='250px' valign='top'>".
$row['luchtvaartmaatschappij'] ."</td>";
$row2html .= "<td width='50px' valign='top'>".
$row['CountLVMPhotos'] . "</td>";
}
$row1html = "</tr>";
$row2html = "</tr>";
echo $row1html . $row2html;
}
There might be more elegant ways but this should work.
If you have a lot of data, that table is gonna get pretty wide though, so hopefully you have a design for that.
<?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
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).
I basically have an input system where people enter data and the data is printed in a specific order in a HTML table.
I have some code which works fine below except that every time the row is updated, the table is edited instead adding a new table with the data. Also when i refresh the data disappears?
My code is below:
$query = "SELECT * FROM rumours";
$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'];
}
$sql="INSERT INTO rumours (band, Title, description)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$connect))
{
die('Error: ' . mysql_error());
}
if (mysql_query($sql, $connect)) {
echo "<table border='1'>";
echo "<tr>";
echo "<td> $title </td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'> $description </td>";
echo "</tr>";
echo "</table>";
}
echo "1 record added";
mysql_close($connect);
You are only generating the table from the inserted db rows, not all of the db rows in the db table. To do that, you have to echo the table code for each of the found rows as well:
$query = "SELECT * FROM rumours";
$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>";
}
$sql="INSERT INTO rumours (band, Title, description)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
/* ... Code truncated to save space */