PHP MySQL Query Where x = $variable from function - php

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);

Related

how to make a query with database as a variable

I have two databases - lorem and nts.lorem - and need to operate with both of them
$user = 'root';
$pass = '';
$db1 = new PDO('mysql:host=localhost; dbname=nts.lorem', $user, $pass);
$db2 = new PDO('mysql:host=localhost; dbname=lorem', $user, $pass);
everything works fine until db is a variable in an ajax request - for example:
js
var db;
if(something is true){db = 'db1';};
else{db = 'db2';}
//... ajax post code
php
function something($db){
global $db1, $db2;
// how to say the next line
$sq = "select id from " . $db . ".tableName order by title asc";
// error - table db1.tableName doesn't exist
}
any help?
Choose connection according to $db value:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
if ($db === 'db1') {
$db1->execute($sq);
} else {
$db2->execute($sq);
}
// rest of the code
}
Add the line that executes the query to your code sample. Without it, it's hard to be sure what's wrong, but I can guess: you don't need the name of the database in the query text, you need to execute the query with the proper database connection, based on the parmeter received from the client.
Something like:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
$stmt = $db === 'db1' ? $db1->query($sq) : $db2->query($sq);
$result = $stmt->fetch();
}
Comment: this assumes you have a table called tableName in both databases.

how do i create a php function to echo out mysql data, a function that can be reused?

I need to write a PHP function to echo out MySQL rows as I give it the SQL query I want to be executed as the function argument. I have tried out the following code but it is giving me an undefined index error
function runQuery($query) {
$conn = mysqli_connect('localhost', 'root', '', 'mydb');
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
the code I am using to call the function is;
runQuery(SELECT * FROM mytable WHERE id='5')
echo $resultset['name'];
this, however, gives me this error, undefined index 'resultset' on line 25. any kind assistance would be appreciated
You dont have a $resultset in the scope of where you call the function. The function creates one, but that is only visible inside the function.
You will also have to put QUOTES around the query, you are passing a string there so it needs to be quoted.
Your errors should have generated quite a few error messages, if you were not getting them I have added 4 lines of code you should add while testing code for example if you are testing on a LIVE server with error reporting turned off.
You should also change the function to ensure you always return something
So amend the call to
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
function runQuery($conn, $query) {
$resultset = [];
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
$resultset = runQuery($conn, "SELECT * FROM mytable WHERE id='5'");
// as result will now be a multidimentional array
// you will need to loop over that to get each returned row
foreach ( $resultset as $row ) {
echo $row['name'];
}
AFTER your edit there is another error
$conn is not created inside the function, so will be invisible in the function code unless passed as a parameter to the function (there is another way but lets not get into the bad habit of using global variables)
First, your code is probably vulnerable to SQL Injection. Please take care of that, by using prepared statements for instance.
https://www.w3schools.com/sql/sql_injection.asp
https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection
Other than that, you do not assign the return value of your function to a variable. You cannot use the $resultset defined in the function scope outside the function, as it is a different scope. Try the following:
$resultset = runQuery("SELECT * FROM mytable WHERE id='5'")
echo $resultset['name'];
I built a similar function recently - here is my code
function returnSQL($conn, $nameSql) {
$result = mysqli_query($conn, $nameSql);
if (!$result) {
return 0;
}
while ($res = mysqli_fetch_assoc($result)) {
$data[] = $res;
}
return $data;
}
The connection is setup outside the function and passed in as an argument along with the sql like this...
$conn = mysqli_connect($servername, $username, $password, $DBName);
if (!$conn) {
echo 'Failed to connect to database :- ' . $DBName . '<br>';
die();
}
$sql = "SELECT * FROM table";
$data = returnSQL($conn, $sql);
I'm no expert, but this works for me :)
What I notice from your code is that you are trying to access $resultset outside of the function it is declared in and I think it is not available as a global variable - perhaps it should be something like:
$returnValue = runQuery(SQL statement);
// $returnValue is assigned the array returned from runQuery()
echo $returnValue['name'];

mysqli_connect in a function throws error

I'm sure the question is easy to answer, but I don't get it.
When I try to connect in a function it throws me an "Access denied for user''#'localhost'" error. It looks like the array isn't available in the array, because the error says I didn't enter a username and password.
The code is:
$config["mysql_host"] = "localhost";
$config["mysql_user"] = "myusername";
$config["mysql_pass"] = "mypass";
$config["db_name"] = "mydb_name";
$config["event_tname"] = "tablename";
function get_events(){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die ("Error, please contact the provider!"/* . mysqli_error()*/); //execute
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
events(); //just an example: call the function
What do I have to change at the array?
Regards,
Franz
At first you should consider using mysqli object-orientated. There is no reason to use procedural style anymore.
Secondly global PHP variables are not available inside of functions, therefore you need to pass the array to the function as explained in the other answer.
See this article for more information on PHPs variable scope.
Imho the best solution would be to use a class for your application and store the config as private attributes. Methods of that class will then have access to the attributes.
just add global $config; inside your function as
function get_events(){
global $config;
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events(); //ju
or pass the config param to function
function get_events($config){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events($config); //ju

I can't get result from mysqli query with PHP (converted from mysql_result)

I have a PHP function that I am converting from using the mysql extension to the mysqli extension.
Everything is going okay, until here. I previously used a mysql_result to get a single piece of data. There is no direct equivalent in mysqli, so I have tried the following but it still doesn't work.
function getdbvalue($table,$value,$idfield,$id) {
$qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
$valueqry = mysqli_query($dbh,$qrytext);
if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
$result = mysqli_fetch_row($valueqry);
$returnvalue = $result[0];
return $returnvalue;
}
I have verified that the variables are passing to the function okay, and the function is actually getting triggered. If I return $id I see the ID numbers.
I don't get an error for the query.
SOLVED:
I needed to add the database connection variable as a global in the function:
Working code:
function getdbvalue($table,$value,$idfield,$id) {
global $dbh; // This was missing!
$qrytext = "SELECT $value FROM $table WHERE $idfield LIKE '$id'";
$valueqry = mysqli_query($dbh,$qrytext);
if (FALSE === $valueqry) die("Select failed: ".mysqli_error);
$result = mysqli_fetch_row($valueqry);
$returnvalue = $result[0];
return $returnvalue;
}
Thanks to everyone for their help. :)
Although it's good idea to automate simple selects, the implementation is highly insecure, and should never be used.
Make it accept SQL query and parameters. It will make it secure.
And also you have to use PDO instead of mysqli
function getdbvalue() {
global $pdo;
$args = func_get_args();
$sql = array_shift($args);
$stm = $pdo->prepare($sql);
$stm->execute($args);
return $stm->fetchColumn();
}
have to be used like this (you have to connect to PDO first):
$name = getdbvalue("SELECT name FROM users WHERE id=?", $is);
this is the only proper way

I'm a little confused, PHP says $results is a non-object of the mysqli class

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();

Categories