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)";
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.
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.
So I have a SQL database with a number of objects in that contain name price and images, I would like to know how I can select them using php and output the result into json
<?php
$db = mysqli_connect ('localhost', 'root', '', 'car_rental') or die ("SQL is Off");
$car = (isset($_GET['car']) ? $_GET['car'] : null);
mysqli_select_db($db,"car_rental");
$SQL = "SELECT * FROM `products` WHERE name LIKE \'%$car%\'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
print $db_field['sku'] . "<BR>";
print $db_field['name'] . "<BR>";
print $db_field['img'] . "<BR>";
print $db_field['price'] . "<BR>";
}
?>
This is my current code car variable will change dependent on car selected
thanks
For getting all values in json format, you need to use like that:
<?
$newArr = array();
while ( $db_field = mysql_fetch_assoc($result) ) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
?>
UPDATE 1:
You are mixing mysqli extension with mysql. Change mysql into mysqli
UPDATE 2:
Why are you connecting database twice in code?
Modified Code:
<?php
$link = mysqli_connect("localhost", "root", "", "car_rental");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$car = (isset($_GET['car']) ? $_GET['car'] : null);
$query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
if ($result = mysqli_query($link, $query)) {
$newArr = array();
/* fetch associative array */
while ($db_field = mysqli_fetch_assoc($result)) {
$newArr[] = $db_field;
}
echo json_encode($newArr); // get all products in json format.
}
?>
Side Note:
Also on PHP error reporting in development phase for saving your time.
I've tried for a couple of days to get all of the data from a MySQL column and put it inside an array, formatted in the following way:
$aSpam= array
( '.info'=> 'i'
, 'anal'=> 'i'
, 'anus'=> 'i'
, 'arse'=> 'i'
)
I've managed to echo it out formatted properly as you can see here: http://www.yourgrumble.com/phpbbforum/getSpam.php
with the following PHP code:
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "db";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT `SpamWord` FROM spamWords";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$counter = 0;
while($row = $result->fetch_assoc()) {
if($counter){
echo ", '" . $row["SpamWord"]. "'=> 'i'";
$counter++;
} else {
echo "'" . $row["SpamWord"]. "'=> 'i'";
$counter++;
}
}
} else {
echo "Error!";
}
$conn->close();
?>
I've read and tried more than 10 solutions found in the web and here at stackoverflow, however none of them worked. I've really got desperate and I cannot get through this without your help guys.
Edit
For example I tried with this solution, but it didn't work:
while ($row = mysql_fetch_array($result))
{
$new_array[$row['id']]['SpamWord'] = $row['SpamWord'];
}
foreach($new_array as $array)
{
echo $array['SpamWord'].'<br />';
}
Thank you all in advance,
Denis Saidov
Try like below:-
$sql = "SELECT `SpamWord` FROM spamWords";
$result = mysqli_query($conn ,$sql) or die(mysqli_error($conn));
$resultArray = array(); // create an array
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$resultArray[$row["SpamWord"]] = 'i'; // assing value
}
} else {
echo "Error!";
}
echo "<pre/>";print_r($resultArray); // print array
$conn->close();
Note: Here you will get your original array containing all SpamWord values comes from database.thanks
PHP array's are like dictionnaries (a list of key/value pairs)
First, before your loop, create your array empty:
$new_array = Array();
while...
Then for each column, you append the column value as a new key for the array
$new_array[$row['SpamWord']] = "i";
As in your example, I put "i" as the value for each array's row.