Harshad Harshad - 7 months ago 24
SQL Question

Please check my SQL query

I'm trying to fetch data using MySQLi Query.
Please check my SQL Query, i'm getting error on the If condition.
i add error which is beside


if condition


when it is getting displayed into console

<?php
$id = $_GET['id'];
include("../include/connection_string.php");


$sql = mysqli_query($db, "SELECT pages, main_id FROM dhms_index_table where main_id='"+$id+"'");

if(mysqli_num_rows($sql)){ // Showing error here " Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result"
$data = array();
while($row = mysqli_fetch_array($sql)){
$data[] = array(
'pages' => $row['pages'],
'main_ID' => $row['main_id']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>


connections_string.php

$server = 'localhost';
$username ="root";
$passwd ='';
$Dbase = 'og_dhms';
$db = @mysqli_connect($server,$username,$passwd)
or die("Could not connect database");
@mysqli_select_db($db, $Dbase)
or die("Could not select database");

Answer

This line

main_id='"+$id+"'

is using + signs rather than dots to concatenate. That is the JS/C method to do that. Maybe you are from that type of background and thought you could use it in PHP; you can't.

so...

main_id='".$id."'

Also make sure you have a value for $id = $_GET['id'];.

Error reporting will tell you if it is or not.

If the GET array is an integer (which I am pretty sure it stands to be), you'd be best to use (int) for it.

$id = (int)$_GET['id'];

and checking if it's set / not empty.

I.e.:

if(isset($_GET['id'])){

    $id = (int)$_GET['id'];

}

or

if(!empty($_GET['id'])){

    $id = (int)$_GET['id'];

}