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.
Related
I am trying to query two tables from a database, while using fetch_assoc() (instead of fetch_row()). The code is below and I am not getting any data from this query. I managed to query the first table, then added some code to query the second one and now I am not getting any output. Any help will be appreciated.
$mysqli = mysqli_connect($servername, $username, $password, "6dwxnmkq", 3314);
if(!$mysqli){
die('Connection failed!');
}
$sql = "SELECT IndexJedlo, Jedlo, Cena, Priloha FROM `jedalny_listok`";
$sql .= "SELECT index, polievka, cena FROM `polievky`";
$jedla = array(8);
$ceny = array(8);
$index = array(8);
$polievky = array(2);
$polievkyCeny = array(2);
$polievkyIndex = array(2);
$i = 0;
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
if($i == 0){
array_push($jedla, $row['Jedlo']);
array_push($ceny, $row['Cena']);
array_push($index, $row['IndexJedlo']);
}else{
array_push($polievky, $row['polievka']);
array_push($polievkyCeny, $row['cena']);
array_push($polievkyIndex, $row['index']);
}
}
$result->free();
}
if ($mysqli->more_results()) {
$i = $i + 1;
}
} while ($mysqli->next_result());
}
$mysqli->close();
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 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.
I have a problem switching from MYSQL to MYSQLi. The codes work fine with MYSQL but when i change the connection to MYSQLi, I received the error as stated above when I'm fetching my query. How can i fetch my queries using mysqli functions?
Code:
function __construct(){
$this->link = mysqli_connect('localhost', 'root', '', 'ajax_rating');
if (!$this->link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($this->link) . "\n";
}
function getItems($id = null){
if(isset($_GET['id']))
{
$query = $this->link->query("SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = $this->link->query("SELECT * FROM items");
}
$rowCount = $query->rowCount();
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
Use num_rows
Read MySQLi row_count
So final answer would be
function getItems($id = null)
{
if(isset($_GET['id']))
{
$query = $this->link->query("SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = $this->link->query("SELECT * FROM items");
}
$rowCount = $query->num_rows;//change here
if($rowCount >= 1)
{
$result = $query->fetchAll();
}
else
{
$result = 0;
}
return $result;
}
EDIT 01
use mysqli_fetch_all instead of fetchAll()
mysqli_fetch_all($query,MYSQLI_ASSOC);
so answer world be
if($rowCount >= 1)
{
$result = mysqli_fetch_all($query,MYSQLI_ASSOC);
}
you can use num_rows for counting rows in DB and you can direct call connection like this :-
//for connection
$con = mysqli_connect("localhost", "root", "", "ajax_rating");
if(!$con)
{
echo "connection error";
}
//query
function getItems($id = null)
{
if(isset($_GET['id']))
{
$query = mysqli_query($con,"SELECT * FROM items WHERE id = '$id'");
}
else
{
$query = mysqli_query($con,"SELECT * FROM items");
}
if (mysqli_num_rows($query) > 0)//change here
{
while($row = mysqli_fetch_assoc($query))
{
$result=$row;
}
}
else
{
$result = 0;
}
return $result;
}