How to put my PHP results into an output variable? - php

The code below selects rows from the database table but I want to select 10 random rows and put them in an output variable like the code below.Not csv in particular but to imitate the one below.
$result = mysqli_query($dbc, "SHOW COLUMNS FROM customer");
$numberOfRows = mysqli_num_rows($result);
if ($numberOfRows > 0) {
$values = mysqli_query($dbc, "SELECT * FROM customer");
while ($rowr = mysqli_fetch_row($values)) {
for ($j=0;$j<$numberOfRows;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
}
print $csv_output;
exit;
First i want to select ten random rows then output them in something like the code above.
My code:
<?php
DEFINE ('DBUSER', '');
DEFINE ('DBPW', '');
DEFINE ('DBHOST', '');
DEFINE ('DBNAME', '');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die("Database selection failed: " . mysqli_error($dbc));
exit();
}
$query = 'Select * FROM Funsies
Order By Rand()
Limit 5';
$result = mysqli_query($dbc, $query);
?>

SELECT name
FROM random AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1
INTO OUTFILE 'c:\\users\\desktop\\file_name.csv'
fields TERMINATED BY ',' enclosed by '"'
LINES TERMINATED BY '\r\n';

Related

count rows with same id and print

So I have this table 'users_photos'. It contains 38k rows with user pictures. Every row contains id, userid and link to the photo. So if a user have 3 pictures, that user id will show in 3 rows in the database.
What I want to do is count the number of users with 1 picture in the database, 2 pictures in the database etc.
UPDATE: I have now the following code
$sql = $mysqli->query("SELECT count(*), count_users from (SELECT u_id, count(*) as count_users FROM users_photos group by u_id) temp group by count_users");
$sql->data_seek(0);
while ($row = $sql->fetch_assoc()) {
echo "".$fetch." = " . $row['count_users'] . "\n<br>";
}
This prints the users that have 1 picture and up to 8. Not how many but only shows that in the database there is users that have 1 picture, 2 pictures etc. Now I need to figure out how to print the total users that have 1 picture etc.
Anyone have any tips? thanks on behalf!
Update Your Query With This
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");
Sql Query:
$sql = $mysqli->query("SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id");
You Can Print like this
// After Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT count(*),u_id as 'count_users' FROM users_photos group by u_id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - count_users" . $row["count_users"]. "<br>";
}
} else {
echo "0 results";
}
You can do something like this:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$sql = 'SELECT u_id, count(*) AS count_users FROM users_photos GROUP BY u_id';
$result = mysqli_query($con, $sql);
while ($row=mysqli_fetch_assoc($result)) {
echo 'User id: ' . $row['u_id'] . ' Count: ' . $row['count_users'] . '<br>';
}
Keep in mind this is just a basic example. In a real world application there is more to do such as checking for errors.

How to write while loop into another while loop for fetch data from SQL query?

I want to get data from two different queries, so first I get data by writing this code:
$sql = "select DATE_FORMAT(tr_date,'%d/%m/%Y %H:%i:%s') as tr_date,p1,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19,p20,tno from rnb_gpl_data where DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i:%s') >= '$s' AND DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i:%s') <= '$e' and did = '$did' order by srno desc limit $offse, $rec_limi";
$retval = mysqli_query($con, $sql);
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
$sqlll = "select * from rnb1_data where DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i') >= '$s' AND DATE_FORMAT(tr_date,'%Y-%m-%d %H:%i') <= '$e' and did = '$did' limit $offse, $rec_limi";
$retval11 = mysqli_query($con, $sqlll);
if(! $retval11 ) {
die('Could not get data: ' . mysqli_error());
}
while($rowww = mysqli_fetch_array($retval11, MYSQL_ASSOC)) {
$bit = $rowww['bitumen_tph'];
$netmixt= $rowww['netmix'];
while($row = mysqli_fetch_array($retval, MYSQL_ASSOC)) {
$jv1=$row['p1'];
echo "<tr > ".
"<td class=\"center\">$jv1</td> ".
"<td class=\"center\">$bit</td> ".
"<td class=\"center\">$netmixt</td> ".
}
}
But my netmixt and bit value remain same for all record. Only jv1 value change according to my database record. I want to update all data according to my database table.
In this image first column is jv1 value second is bit and third is netmix.
You can see that bit and netmix value remain same for all rows but actually it differ in database table.

PHP Run query on SHOW TABLES results

How do I go about running a query on tables from a previous SHOW TABLES query? What I'm trying to do is create a PHP script that runs every 24 hours that sorts a table by "verified" descending and "votes" descending and update "nomnom" on the top result, for every table in the database.
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan = (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE " . $row[0] . " SET nomnom=0 verified=0; UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $row[0] . ' done<br>';
}
} else {
echo 'query 0';
}
This correctly echos every table name followed by done, but isn't actually updating the tables. What am I missing?
UPDATE
So I've determined that the following should work:
$sql = "SET #clan := (SELECT `clan` FROM " . $row[0] . " ORDER BY `verified` DESC, `votes` DESC LIMIT 1); UPDATE " . $row[0] . " SET `nomnom`=0, `verified`=0; UPDATE " . $row[0] . " SET `nomnom`=1 WHERE `clan`=#clan";
by echoing $sql and running the queries returned through phpmyadmin without changing anything.
Here's a line that is echoed.
SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
It just for some reason isn't actually doing it when using
$conn->query($sql);
UPDATE 2
Figured out a way to make it work. Would mark my answer but I can't for 2 days...
Try this query
$sql = SET #clan := (SELECT clan FROM aerngardh ORDER BY verified DESC, votes DESC LIMIT 1); UPDATE aerngardh SET nomnom=0, verified=0; UPDATE aerngardh SET nomnom=1 WHERE clan=#clan
This should work
Had to split the query into 3 separate queries. Full working code:
$conn = new MySQLi($servername, $username, $password, $dbname);
$result = $conn->query("SHOW TABLES");
if($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$sql = "SET #clan := (SELECT clan FROM " . $row[0] . " ORDER BY verified DESC, votes DESC LIMIT 1);";
$sql2 = "UPDATE " . $row[0] . " SET nomnom=0, verified=0;";
$sql3 = "UPDATE " . $row[0] . " SET nomnom=1 WHERE clan=#clan";
$conn->query($sql);
echo $conn->error . '<br>';
$conn->query($sql2);
echo $conn->error . '<br>';
$conn->query($sql3);
echo $conn->error . '<br>';
}
} else {
echo 'query 0';
}
If anyone would like to post how to make this a proper multi_query without getting queries out of sync errors, be my guest. I cba doing that lol.

I want to use two where conditions in php to get data from mysql

My problem is this:
<?php
// Connect to database server
mysql_connect("localhost", "root", "abcabc") or die (mysql_error ());
// Select database
mysql_select_db('iite') or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo'<h1>'. $row['title'].'</h1>';
echo'<h1>'. $row['price'].'</h1>';
}
// Close the database connection
mysql_close();
?>
I want to show related posts, for this I need to insert this:
$sql = "SELECT * FROM table1 where title like '%keyword%' limit 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["price"]. " " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
so how can I insert the related post part near
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
and how to echo?
Thanks
You can use OR or AND for combining different where conditions(according to requirement) in query :
Ex;
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5";
$strSQL = mysql_query(SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5) or die(mysql_error());
$row_strSQL = mysql_fetch_assoc($strSQL );
$totalRows_strSQL = mysql_num_rows($strSQL );
if ($result->totalRows_strSQL > 0) {
// output data of each row
while($row_strSQL= $result->fetch_assoc()) {
echo "id: " . $row_strSQL["id"]. " - Name: " . $row_strSQL["price"]. " " . $row_strSQL["title"]. "<br>";
}
} else {
echo "0 results";
}
You don't need two seperate queries for that at all. Just use the OR operator in ur where clause like Where id=" . $_GET['id']." or title like '%keyword%'

How to optimize queries in mysql

My mysql query for search is :
$result = mysql_query("SELECT * FROM room_tb WHERE location ='{$location}' AND price BETWEEN '$minprice' AND '$maxprice' ")or die('Could not connect: ' . mysql_error()); ;
This makes a compulsion to enter both the location and min and max price in form.
I want a query that can make user to enter either location or max and min price, as well as allow user to search by both fields. What should i do?
When I am generating my queries with optional fields, I create an array of each field, then join them with implode
$query_array = array();
$queries_stringed = '';
if(strlen($location) > 0){
$query_array[] = "location ='{$location}'";
};
if(strlen($minprice) > 0 && strlen($maxprice) > 0){
$query_array[] = "(price BETWEEN '$minprice' AND '$maxprice')";
};
if(!empty($query_array)){
$queries_stringed = "WHERE ".implode(" AND ", $query_array);
};
$result = mysql_query("SELECT * FROM room_tb $queries_stringed");
Thsi ought to do it for you :
$query = "SELECT * FROM room_tb ";
if($location){
$query .= " WHERE location ='{$location}' ";
}
if(($minprice)&&($maxprice)&&(!$location)){
$query .= " WHERE price BETWEEN '$minprice' AND '$maxprice'";
}
if(($minprice)&&($maxprice)&&($location)){
$query .= " AND price BETWEEN '$minprice' AND '$maxprice'";
}
$result = mysql_query($query)or die('Could not connect: ' . mysql_error());
Cheers
As an addition to those answers - you shouldn't trust users inputs and should escape given strings or use PDO instead of mysql_ functions

Categories