Reputation: 109
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");
Upvotes: 0
Views: 119
Reputation: 346
Your issue was most likely caused by a query syntax error here:
main_id='"+$id+"'
Changing that to this, should solve the issue:
main_id='".$id."'
But you should not use pure unfiltered user input in your sql statements. I would do something like this:
<?php
$id = $_GET['id'];
include("../include/connection_string.php");
if($stmt = mysqli_prepare($db, "SELECT pages, main_id FROM dhms_index_table WHERE main_id = ?")) {
mysqli_stmt_bind_param($stmt, 'i', $id);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
mysqli_stmt_bind_result($stmt, $pages, $main_id);
$data = array();
while(mysqli_stmt_fetch($stmt)) {
$data[] = array(
'pages' => $pages,
'main_ID' => $main_id
);
}
header('Content-type: application/json');
echo json_encode($data);
}
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
}
?>
Always make sure to use prepared statements when you are including user input on statements to avoid SQL Injection.
Read more about it here: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I hope it helped.
Upvotes: 0
Reputation: 74232
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'];
}
Upvotes: 3