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");
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'];
}
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.
Related
Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);
I'm currently getting the error "Fatal Error: Cannot pass parameter 3 by reference in Update.php on line 14. I need to know how I can fix this.
Here's Update.php:
<?php
$post_json = file_get_contents("php://input");
$post = json_decode($post_json, true);
$response = array();
$configs = include('config.php');
$mysqli = new mysqli($configs["host"], $configs["username"], $configs["password"], "Account"); if($mysqli->connect_errno){
die("Error connecting to MySQL database (".$mysqli->connect_errno.") ".$mysqli->connect_error);
}
$name = $post["Name"];
$rank = $post["Rank"];
$perm = (int) $post["Perm"];
$stmt = $mysqli->prepare("UPDATE accounts SET `rank`=?,`rankPerm`=? WHERE `name`=?");
$stmt->bind_param("sis", $rank, (int) $perm, $name);
$stmt->execute();
?>
I believe that the error is in the (int) part of line 14, but I don't know what's wrong.
I'm trying to edit the "rank" part of one of these rows with this PHP file when executed:
http://imgur.com/a/Ms639
Thanks for all of your help in advance!
NOTE: Already checked update existing row in mysql using php coding
use this
<?php
$post_json = file_get_contents("php://input");
$post = json_decode($post_json, true);
$response = array();
$configs = include('config.php');
$mysqli = new mysqli($configs["host"], $configs["username"], $configs["password"], "Account"); if($mysqli->connect_errno){
die("Error connecting to MySQL database (".$mysqli->connect_errno.") ".$mysqli->connect_error);
}
$name = $post["Name"];
$rank = $post["Rank"];
$perm = (int) $post["Perm"];
$sis="sis";
$stmt = $mysqli->prepare("UPDATE accounts SET `rank`=?,`rankPerm`=? WHERE `name`=?");
$stmt->bind_param($sis, $rank, $perm, $name);
$stmt->execute();
?>
I believe you have to pass variables rather than a string.
Or you could use bindvalue() instead of bindparam() if you're using PDO.
From Php.net
Note:
Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.
It seems when you add a type conversion as a parameter to a function Php doesn't keep the reference, if you remove the (int) in the function call should be fine.
$stmt->bind_param("sis", $rank, (int) $perm, $name);
To
$stmt->bind_param("sis", $rank, $perm, $name);
May be this is the problem...
$name = $_post["Name"];
$rank = $_post["Rank"];
$perm = (int) $_post["Perm"];
I'm having problems with a PHP script that returns some info based on a supplied array of identifiers (MAC addresses).
It gives me a 500 unspecified error.
if (!isset($_POST['macs'])) {
echo 'Please enter mac addresses!';
die;
}
$mysqli = new mysqli("x", "x", "x", "x");
/* check connection */
if ($mysqli->connect_error)
die("$mysqli->connect_errno: $mysqli->connect_error");
$stmt = $mysqli->stmt_init();
/* create a prepared statement */
$query = "SELECT username, mac FROM user WHERE mac IN (" . str_repeat("?,", count($_POST['macs']));
$query = rtrim($query, ",");
$query = $query . ')';
if ($mysqli->prepare($query)) {
call_user_func_array(array($stmt, "bind_param"), array_merge(array('s'), $_POST['macs']));
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['username'];
}
/* close statement */
mysqli_stmt_close($stmt);
}
mysqli_close($link);
This is what I'm posting via the Postman Chrome app:
macs[0] = 'F0:72:8C:F3:B5:66'
macs[1] = 'FA:72:8C:F3:B5:66'
Can anyone at least hint me at what's causing the problem. I'm guessing it's the call_user_func_array call but, I'm unsure of what's the actual problem.
// If you bind array-elements to a prepared statement, the array has to be declared first with the used keys:
Coming to the problem calling mysqli::bind_param() with a dynamic number of arguments via call_user_func_array() with PHP Version 5.3+, there's another workaround besides using an extra function to build the references for the array-elements.
You can use Reflection to call mysqli::bind_param().
Example:
<?php
$db = new mysqli("localhost","root","","tests");
$res = $db->prepare("INSERT INTO test SET foo=?,bar=?");
$refArr = array("si","hello",42);
$ref = new ReflectionClass('mysqli_stmt');
$method = $ref->getMethod("bind_param");
$method->invokeArgs($res,$refArr);
$res->execute();
for more
http://php.net/manual/en/mysqli-stmt.bind-param.php#104073
So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.
I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();