PHP and MySQLi multiple queries in a single string - php

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.

Related

Issues ordering a resut from query

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

PHP - MySql SELECT WHERE value = string JSON

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)";

Cannot update mysql column from PHP

I am trying to update a column of a database's table using this
$url = mysqli_connect($servername, $dbusername, $usrpassword, $dbname);
// Check connection
if (!$url) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT adv_val FROM current_advert";
if($result = mysqli_query($url, $sql)){
while($row = mysqli_fetch_assoc($result)){
$adv_val = $row['adv_val'];
}
}
echo "current advert is:" . $adv_val;
// Attempt select query execution
$sql = "SELECT advert_text FROM advertisements WHERE advert_id = $adv_val";
if($result = mysqli_query($url, $sql)){
while($row = mysqli_fetch_assoc($result)){
$advert = $row['advert_text'];
}
}
echo "<br>current advert text is:" . $advert;
if ($adv_val == 1 OR $adv_val == 2 OR $adv_val == 3) {
$adv_val = $adv_val + 1;
} else {
$adv_val = 1;
}
$sql = "UPDATE current_advert SET adv_val='$adv_val'";
// Close connection
echo "<br>next advert id is:" . $adv_val;
mysqli_close($url);
The connection to the database is ok since i'm able to read data from it in the beginning of my script. This is killing me!
$sql = "UPDATE current_advert SET adv_val='$adv_val'";
mysqli_query($url, $sql);
you are missing the 2nd line.

PHP/MYSQL query failing but no error

My mySQLi query is failing but the error is blank. Can anybody tell me what the problem is, or how I can output info on the error?
Heres my PHP code:
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['in_wordarray']))
{
$words = $_POST['in_wordarray'];
$sql = "SELECT *, (";
$i = 0;
foreach ($words as $value) {
if($i == 0) {
$sql .= "(`words` LIKE '%$value%')";
} else {
$sql .= " + (`words` LIKE '%$value%')";
}
$i++;
}
$sql .= ") AS `numMatches` FROM `mytable` HAVING `numMatches` >= 3 ORDER BY `numMatches` DESC";
//echo $sql;
$result = $conn->query($sql);
if ($result === TRUE) {
$text_result_array = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$text_result_array[] = $row;
}
// Encode the response
echo json_encode($text_result_array);
}
} else {
echo $conn->error;
}
} else {
echo "Bad Input";
}
And the resulting SQL query looks like this:
SELECT *, ((`words` LIKE '%word1%') + (`words` LIKE '%word2%') + (`words` LIKE '%word3%')) AS `numMatches` FROM `words`HAVING `numMatches` >= 3 ORDER BY `numMatches` DESC
Sorry I'm not so experienced with php alone, but are you sure this returns a Boolean?
$result = $conn->query($sql);
If not can you remove that if statement?
I wrote it as an answer because sadly I can't comment yet.

php script just stops even with set_time_limit(0)

I have looked at like 10 other posts with people who seem to have the same problem as me in, most suggest putting set_time_limit(0);. But even with that no matter what script I run, always after around 9-10 minutes it just stops.
I have tried so many combinations of the below 3 variables, setting them to -1, 0, 9999999; just always stops. It was not so long ago, I had the exact same script below run over night. And just one day I have this problem with any script.
I’m 100% sure it’s stopping before its finished, and it’s not stopping due to error. Because any of my scripts now stop at the same app run time.
Extremely frustrated, any help will be much appreciated.
In php.ini:
max_input_time = -1
max_execution_time = 0
set_time_limit = 0
Another scripts: (also stops after 10 minutes)
<?php
set_time_limit(0);
ignore_user_abort(true);
function categoryinsert($english, $name, $keywords, $language)
{
if(!$english)
{
echo "no english recieved! in categoryinsert<br />";
return 0;
}
else if(!$name)
{
echo "no name recieved! in categoryinsert<br />";
return 0;
}
else if(!$language)
{
echo "no language recieved! in categoryinsert<br />";
return 0;
}
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "INSERT INTO `categories` (english, name, keywords, language) values ('$english','$name','$keywords','$language');";
$QueryResult = mysqli_query($DBConnect, $qwry);
//Or die("<p>Unable to execute the query.[".$qwry."]<p>"
//. "<p>Error code " . mysqli_errno($DBConnect)
//. ": " . mysqli_error($DBConnect)) . "</p>";
mysqli_close($DBConnect);
}
function checkfor($english, $lang)
{
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "SELECT * FROM `categories` where english = '$english' and language = '$lang';";
$QueryResult = mysqli_query($DBConnect, $qwry);
$Row = mysqli_fetch_row($QueryResult);
mysqli_close($DBConnect);
if($Row) return true;
else return false;
}
function categoryupdate($keywords, $language, $english)
{
if(!$english)
{
echo "no english recieved! in categoryupdate<br />";
return 0;
}
else if(!$keywords)
{
echo "no keywords recieved! in categoryupdate<br />";
return 0;
}
else if(!$language)
{
echo "no language recieved! in categoryupdate<br />";
return 0;
}
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "UPDATE `categories` set keywords = '$keywords' where language = '$language' and language = '$language';";
$QueryResult = mysqli_query($DBConnect, $qwry)
Or die("<p>Unable to execute the query.[".$qwry."]<p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
mysqli_close($DBConnect);
}
function translatekeywords($keywords, $tolang)
{
if(!$keywords)
{
echo "no keywords recieved! in translatekeywords<br />";
return 0;
}
else if(!$tolang)
{
echo "no tolang recieved! in translatekeywords<br />";
return 0;
}
$parts = explode(", ", $keywords);
$count = 0;
$out = "";
while($parts[$count])
{
if(($count != 0) and ($result)) $out = $out . ", ";
$result = translate($parts[$count], 'eng', $tolang);
if($result) $out = $out . $result;
$count++;
}
return $out;
}
include '../functions.php';
$DBConnect = mysqli_connect("localhost", "USER***", "************");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "db***");
$qwry = "SELECT english, keywords FROM `categories` where language = 'eng' order by name ASC;";
$QueryResult = mysqli_query($DBConnect, $qwry)
Or die("<p>Unable to execute the query.[".$qwry."]<p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
$count = 0;
$Row = mysqli_fetch_row($QueryResult);
do
{
$categories[$count] = $Row;
echo $count.') ['.$categories[$count][0].']['.$categories[$count][1].']<br />';
$Row = mysqli_fetch_row($QueryResult);
$count++;
}while($Row);
$qwry = "SELECT ISO3 FROM `languages` order by name ASC;";
$QueryResult = mysqli_query($DBConnect, $qwry)
Or die("<p>Unable to execute the query.[".$qwry."]<p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
$count = 0;
$Row = mysqli_fetch_row($QueryResult);
do
{
$languages[$count] = $Row[0];
$Row = mysqli_fetch_row($QueryResult);
echo '['.$languages[$count].']<br />';
$count++;
}while($Row);
$lcount = 0;
do
{
if($languages[$lcount] != 'eng')
{
$ccount = 0;
do
{
if(!checkfor($categories[$ccount][0], $languages[$lcount]))
{
$name = translate($categories[$ccount][0], 'eng', $languages[$lcount]);
if($categories[$ccount][1]) $keywords = translatekeywords($categories[$ccount][1],$languages[$lcount]);
categoryinsert($categories[$ccount][0], $name, $keywords, $languages[$lcount]);
}
$ccount++;
}while($categories[$ccount]);
}
$lcount++;
}while($languages[$lcount]);
mysqli_close($DBConnect);
echo "FINISHED! [$lcount] languages proccessed";
?>
The script:
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<body>
<?php
set_time_limit(0);
ignore_user_abort(true);
include 'functions.php';
function insertsentence($sentence, $lang, $id, $user)
{
if(($lang == 'epo') and (strlen($sentence) < 255) )
{
$DBConnect = mysqli_connect("localhost", "xxxxx_userx", "xxxxxxx!");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "xxxxx_main");
$insertqwry = "INSERT INTO `sentences` (sentence, user, id, language) VALUES ('".withslashes($sentence)."', '".withslashes($user)."', '".withslashes($id)."', '".withslashes($lang)."');";
$QueryResult = mysqli_query($DBConnect, $insertqwry) ;
//Or die("<p>Unable to execute the query.[".$insertqwry."]<p>"
//. "<p>Error code " . mysqli_errno($DBConnect)
//. ": " . mysqli_error($DBConnect)) . "</p>";
mysqli_close($DBConnect);
return 1;
}
}
$myFile = "sentences_detailed.csv";
$fh = fopen($myFile, 'r');
$s = fread($fh, 3);
if ($s != pack('CCC',0xef, 0xbb, 0xbf)) {
// bom not found, rewind file
fseek($fh, 0, SEEK_SET);
}
$count = 0;
ob_start();
do
{
$line = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', withslashes(trim(fgets($fh))));
$parts = explode(" ", $line);
$id = $parts[0];
$lang = $parts[1];
$sentence = withslashes($parts[2]);
$user = withslashes($parts[3]);
$note = "";
if ((!$line) or ($line == "") or ($line == "!"))
{
echo ($count-1)." entries were processed<br />";
echo "done<br />";
exit();
}
if ($sentence != "!" )
{
if (insertsentence($sentence, $lang, $id, $user))
echo "!";
}
ob_flush();
flush();
$count++;
echo ".";
}while($line);
fclose($fh);
mysqli_close($DBConnect);
echo ($count-1)." entries were processed<br />";
?>
</body>
</html>
EDIT: No matter what script I run, or how simple it always stops after about 10 minutes. So I doubt it’s anything to do with the code in my script. So I'll add that my web server I’m running scripts on, is on Bluehost.
The answer is its a limitation bluehost has set to my account. Heres the response he gave me:
...
The Dedicated IP (+$3.33 per month) will increase the limits on the account.
The following it the limits on how the server will kill processes with and without the Dedicated IP on the account:
With a Dedicated IP Without Dedicated IP
Apache/Web (HTML/PHP/Downloads) 12 hours 10 minutes
...
Consider using flush function of PHP, with this you can execute your loop continuously - I know this is not the best and final solution but this might helpful to you :)
See this first example
Some ideas.
First your code has these calls to a function called withslashes() which I assume is a custom function designed to add slashes (aka: escape) values to quotes & other characters But you are using MySQLi calls, right? Then why not avoid reinventing the wheel and just use mysqli_real_escape_string() which is part of the MySQLi extensions?
Also, I added mysqli_free_result() which “Frees the memory associated with a result.” Which can’t hurt even if the result of your query is just an acknowledgement that the query ran.
And I added a sleep() value of ` second to at least throttle the process a bit to give your server room to breath.
The whole goal is to use built-in PHP functions to avoid using more RAM than necessary when running MySQL queries & pausing the script by 1 second to give it breathing room.
Here is a refactored version of insertsentence() using the first set of ideas to improve performance:
function insertsentence($sentence, $lang, $id, $user) {
if (($lang == 'epo') and (strlen($sentence) < 255)) {
$DBConnect = mysqli_connect("localhost", "xxxxx_userx", "xxxxxxx!");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "xxxxx_main");
$insertqwry = "INSERT INTO `sentences` (sentence, user, id, language)"
. " VALUES ('$sentence', '$user', '$id', '$lang');"
;
// Escape the query.
$insertqwry = mysqli_real_escape_string($DBConnect, $insertqwry);
$QueryResult = mysqli_query($DBConnect, $insertqwry) ;
// Free the result set.
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
// Sleep for 1 second.
sleep(1);
return TRUE;
}
}
But why not use mysqli_stmt_bind_param() to make full use of the prepared statements capability of MySQLi? Then you no longer need to use mysqli_real_escape_string() because prepared statements basically handle all of that.
With that in mind, here is another refactored version of insertsentence() which uses mysqli_stmt_bind_param():
function insertsentence($sentence, $lang, $id, $user) {
if (($lang == 'epo') and (strlen($sentence) < 255)) {
$DBConnect = mysqli_connect("localhost", "xxxxx_userx", "xxxxxxx!");
mysqli_set_charset($DBConnect, "utf8");
mysqli_select_db($DBConnect, "xxxxx_main");
$insertqwry = "INSERT INTO `sentences` (sentence, user, id, language)"
. " VALUES (?, ?, ?, ?);"
;
// Bind the values to the statement.
mysqli_stmt_bind_param($insertqwry, 'ssis', $sentence, $user, $id, $lang);
$QueryResult = mysqli_query($DBConnect, $insertqwry) ;
// Free the result set.
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
// Sleep for 1 second.
sleep(1);
return TRUE;
}
}
Note the 'ssds' in mysqli_stmt_bind_param(). Each letter determines the types of your 4 values. So in this case it is string (sentence), string (user), integer (id), string (language) which is my best guesses based on the data you’re giving me.
Sounds like your script is limited by the server. I think you can change this in php.ini.

Categories