I am trying to order a 2nd query inside of a query loop, but doesn't seem to work... What I exactly want to achieve is to order the rows by ID, but at the 2nd query it doesn't work.
Here is the code:
<table>
<?php
function convertToHoursMins($time, $format = '%02d:%02d') {
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
return sprintf($format, $hours, $minutes);
}
$servername = "xxxx";
$username = "xxxxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!$_GET["steam"])
{
$steam = $steamprofile['steamid'];
}
else
{
$steam = intval($_GET["steam"]);
}
$sql = "SELECT * FROM `TotalVIPs`";
$conn->set_charset("utf8");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo " <tr><th>". $row["SteamID"]."</th><td></tr>";
$sql2 = "SELECT * FROM `PlayedTime` WHERE `steamid` LIKE '". $row["SteamID"] ."' ORDER BY id ASC";
$conn->set_charset("utf8");
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$time = $row2["AllTotal"];
$convtime = convertToHoursMins($time, '%d ore %d min');
$steamprof = "<a href='profile.php?steam=" . $row2["communityid"]. "' class='btn btn-default btn-xs'>Profil</a>";
echo " <tr><th>". $row2["id"]."</th><td>". $row2["playername"]."</td><td>". $row2["steamid"]."</td><td>". $convtime ."</td><td>". $row2["last_accountuse"]."</td><td>" . $steamprof . "</tr>";
}
}
}
}
$conn->close();
?>
</table>
I want it to order by ID, but doesn't do it for some reason.
Here, a photo: http://prntscr.com/neuu74
Since you're using nested loops, the overall results will be ordered by the results from the first query, and it will only order by id within each of the outer query's rows.
Instead, you should use a single query that joins the two tables, then you can order by a column in the second table.
SELECT *
FROM TotalVIPs AS v
JOIN PlayedTime AS p
ON p.steamid = v.steamid
ORDER by p.id
Related
Here's what i tried.
I've Tried fetch the data from DB.It shows data from the start of the iteration to the End of iteration.I need only last iteration value.I'm a complete noob. A help would be appreciated
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[]= $row;
// echo "<pre>";
// print_r($myarray);
echo "<pre>";echo json_encode($myarray);
// echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Description :" . $row["description"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Change your SQL query to
SELECT id, name, description FROM products order by id desc limit 1
That will work for you.
Finally, I got your point that what you want-
You need to get all record in one variable.Which you can encode at last
For that do like below:-
1.Initialize array outside of the loop
2.Assign each record to the array inside the loop
3.Encode array outside the loop
Do like below:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "api_db";
$conn = new mysqli($servername, $username, $password, $dbname);
$myarray=array();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM products";
$result = $conn->query($sql);
$myarray = []; //Initialize array outside of the loop
if ($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQL_ASSOC)) {
$myarray[] = $row; //Assign each record to the array inside the loop
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($myarray);//Encode array outside the loop
?>
While it looks like a duplicate to me, I would suggest the following, assuming that you are not intending to sort the dataset from the DBMS.
Use mysqli_data_seek ( mysqli_result $result , int $offset ) to move cursor that traverses the dataset. So for your case it would be
$nor = mysqli_num_rows($result); //Number of rows
mysqli_data_seek($resutl, ($nor - 1)); //Indices are based on 0
Basically $nor contains the total number of records. So the index of the last ever record would be $nor-1.
Of course if you are sorting the dataset in your query using ORDER BY, then the best way to do this is appending ORDER BY id DESC LIMIT 1.
I've got a number of variables that need to be looked up in a MySQL database, their values replaced with database entries, and then put together in a single string to display to the end user, code below.
I've created the below code, which while it technically works, looks really messy. Basically I'm having to look up each variable directly before it appears in the string (using the below)
$xxx = $conn->query($xxx);
This creates for really messy looking code, and also results in multiple database queries which no doubt will slow my site down. Is there a more efficient way to do this that I'm missing out on?
Any help would be greatly appreciated
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$airlinequery = "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30;";
$depairportquery = "SELECT * FROM `airportdata` WHERE `airportcode` = '$depdest' LIMIT 0 , 30;";
$arrairportquery = "SELECT * FROM `airportdata` WHERE `airportcode` = '$arrdest' LIMIT 0 , 30;";
$bookingclassquery = "SELECT $bookingclass FROM `bookingclass` WHERE `airline` = '$airline' LIMIT 0 , 30;";
$utctakeoffquery = "SELECT `timezonehours`,`timezoneminutes`,`timezone` FROM `airportdata` WHERE `airportcode`= '$depdest';";
$utcarriveoffquery = "SELECT `timezonehours`,`timezoneminutes`,`timezone` FROM `airportdata` WHERE `airportcode`= '$arrdest';";
if(!$result = $conn->query($airlinequery)){
die('There was an error running the query [' . $conn->error . ']');
}
$result = $conn->query($airlinequery);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$date=date_create($depdate);
echo date_format($date,"D d M"). " - ". $airline." ".$flightno;
}
}
$cabinresult = $conn->query($bookingclassquery);
if ($cabinresult->num_rows > 0) {
while($cabinrow = $cabinresult->fetch_assoc()) {
echo $cabinrow[$bookingclass];
}
}
$dresult = $conn->query($depairportquery);
if ($dresult->num_rows > 0) {
while($drow = $dresult->fetch_assoc()) {
$arr = explode(' ',trim($drow['airportname']));
if ($arr[0] == $drow['cityname']){
$drow['cityname'] = "";
}else{
$drow['cityname']= " ".$drow['cityname'];
}
echo "Depart: " .$drow['airportname'].",".$drow['cityname']." (".$drow['airportcode'].") at " . $deptime."<br>";
}
}
$aresult = $conn->query($arrairportquery);
if ($aresult->num_rows > 0) {
while($arow = $aresult->fetch_assoc()) {
$arr = explode(' ',trim($arow['airportname']));
if ($arr[0] == $arow['cityname']){
$arow['cityname'] = "";
}else{
$arow['cityname']= " ".$arow['cityname'];
}
echo "Arrive: " .$arow['airportname'].",".$arow['cityname']." (".$arow['airportcode'].") at " . $arrtime .$nextday."
";
$arrdate ="";
}
}
$conn->close();
This should be a comment, but its a bit long and will be hard to read....
SELECT *
Why are you selecting all the attributes from the table when you don't need them? You've not provided the table structures which would inform a number of choices about a solution here. If these issues had been addressed we might have been able to advise whether a UNION or VIEW would apposite.
while($row = $result->fetch_assoc()) {
$date=date_create($depdate);
echo date_format($date,"D d M"). " - ". $airline." ".$flightno;
}
What is $depdate? $airline? $flightno? Are these supposed to be values retrieved from $row? Your loop body never references $row. There are similar issues for all your queries.
through a cURL connection, I can pick up data, from Json files, placed on a remote server. In particular, the codes of some products, which thanks to a foreach
foreach($data['results'] as $key=>$val){
$codici_hotel = $val['hotel_code'];
echo $codici_hotel.",";
}
I can see on video:
1074d0,19f726,1072ba,107104,183444,112438,15d8ab,1b326e,19d885,189b95,1071bf,107155,193e61,10aab2,138752,18dd7d,19d7f9,117b0d,1071b8,1398c4,107039,110851,107124,110669
Now I need to use that string to run a select on a local database, such as:
$sql = "SELECT * FROM hotels WHERE code = ('$codici_hotel')";
What is the correct sql string?
Thanks for your help
CODE UPDATE USED
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$conn2 = new mysqli($servername, $username, $password, $dbname);
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql2 = "SELECT name FROM hotels WHERE code IN ('$codici_hotel')";
$result2 = $conn2->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row2 = $result2->fetch_assoc()) {
$nome_hotel = $row2["name"] ;
}
} else {
echo "0 results";
}
$conn2->close();
echo $nome_hotel;
You have to convert your all codes in string enclosed with '. Then use IN clause of mysql. change your code as below
$codici_hotel_arr = array();
foreach($data['results'] as $key=>$val){
$codici_hotel_arr[] = $val['hotel_code'];
}
$codici_hotel = "'".implode(",",$codici_hotel_arr)."'";
$sql = "SELECT * FROM hotels WHERE code IN ($codici_hotel)";
I am having an add row "age" with sorting data in a table by clicking on column name. I tried many solutions for this, but nothing works. I need the new column "age":
TIMESTAMPDIFF(YEAR,CURDATE(),geburtstag) from members
<?php
// first creating database connection
$servername = "localhost";
$username = "user";
$password = "password";
$database = "celebrates"; //this will contain name of a database
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
mysqli_set_charset($conn, "utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$action = '';
$sql = "SELECT * from members";
$where = '';
if(isset($_GET["id"]))
{
$id = $_GET["id"]; //geting id value which we are passing from table headers
$action = $_GET["action"]; // geting action value which we are passing from table headers
//we are checking condition if $action value is ASC then $action will set to DESC otherwise it will remain ASC
if($action == 'ASC')
{
$action='DESC';
} else {
$action='ASC';
}
if($_GET['id']=='id') {
$id = "id";
} elseif($_GET['id']=='name') {
$id = "name";
} elseif($_GET['id']=='vorname') {
$id="vorname";
} elseif($_GET['id']=='geburtstag') {
$id="geburtstag";
} elseif($_GET['id']=='age') {
$id = "age";
} elseif($_GET['id']=='ort') {
$id = "ort";
}
$where = " ORDER BY $id $action ";
$sql = "SELECT * FROM members " . $where;
}
?>
<!DOCTYPE html>
<html lang="de">
<table>
<tr>
<th>NAME</th>
<th>VORNAME</th>
<th>GEBURTSTAG</th>
<th>ORT</th>
<th>AGE</th>
</tr>
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Fetch a result row as an associative array
while($row = $result->fetch_assoc()) {
?>
<tr>
<td><?php echo $row["name"];?></td>
<td><?php echo $row["vorname"];?></td>
<td><?php echo date("j. F Y", strtotime($row["geburtstag"]));?></td>
<td><?php echo $row['ort'];?></td>
<td><?php echo $row['age'];?></td>
</tr>
<?php
}
echo '</table>';
echo '</div>';
} else {
echo "0 results";
}
$conn->close();
Notice: Undefined index: age in line : "php echo $row['age']"
Can you help me? Thanks.
You probably do not have an column called age in your members table. Just enhance your query a little bit:
$sql = "SELECT members.*, TIMESTAMPDIFF(YEAR,CURDATE(),geburtstag) as age FROM members " . $where
You can't calculate age subtracting years, because the age is calculated also considering days.
Use this query:
SELECT *,
YEAR( CURRENT_TIMESTAMP ) - YEAR( geburtstag ) - (SUBSTR(CURRENT_TIMESTAMP,6,5 ) < SUBSTR(geburtstag,6, 5)) as age
FROM members
sqlFiddle demo
By this query, you subtract 1 from years difference if current month/day (SUBSTR(CURRENT_TIMESTAMP,6,5) ) is smaller than birthday month/day ((SUBSTR(geburtstag,6, 5))
I've been trying to execute a multiple query, so I've searched for a better approach on how to do this and I've read this mysqli_multi_query in php.
I tried it on my own to see the results, but it keeps on giving me error. Here's the code:
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '".$studid."'";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'";
if (mysqli_multi_query($conn, $sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
With the code above, it will just print error from the else statement I set. I also tried changing the second query to $sql .= "SELECT * FROM tbl_classes WHERE class_code = '".$classcode."'"; and also tried putting semicolon after the first query to tell the SQL that I'm done with the first query since I'm putting 2 strings together, but still no luck.
try this
$studid = $_GET['stud_id'];
$classcode = $_GET['class'];
$conn = new MySQLi($host, $username, $password, $dbname) or die('Can not connect to database');
$sql = "SELECT * FROM tbl_students WHERE stud_id = '$studid';";
$sql.= "SELECT * FROM tbl_classes WHERE class_code = '$classcode'";
if ($conn->multi_query($sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
$studname = $row[3].", ".$row[1];
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
$studname = $row['fname'];
}
} while (mysqli_more_results($conn));
}else{ echo "error";}
$conn->close();
Make one query instead of two :
"SELECT ts.*, tc.*
FROM tbl_students as ts, tbl_classes as tc
WHERE ts.stud_id = '$studid'
AND tc.class_code = '$classcode'"
Note : If you get redundant data then use group by.