Mysqli about security in a function - php

function get_articles_on_home(){
global $connection;
$query = "SELECT * FROM articles ORDER BY position ASC"
$output = mysqli_query($connection, $query);
confirm_query($output);
return($output);
}
Should I prepare this function securely or encode data, or is it fine since the user is not entering anything at this point? And if so, how would I do it? Thanks

Since you don't deal with any user input there is no way of injecting your query, but you have a syntax error, probably a typo. You are missing a semicolon ; right after your query
$query = "SELECT * FROM articles ORDER BY position ASC"; //here was missing

Related

How to prepare statement with mysqli for select query

I am very worried about sql injection. I have been reading up about it and been trying to prepare the following query:
$query_AcousticDB = "SELECT * FROM products WHERE Category = 'Acoustic ' ORDER BY RAND()";
$AcousticDB = mysqli_query($DB, $query_AcousticDB) or die(mysqli_connect_error());
$row_AcousticDB = mysqli_fetch_assoc($AcousticDB);
$totalRows_AcousticDB = mysqli_num_rows($AcousticDB);
which works great.
I thought that I only have to change to the following:
$query_AcousticDB = prepare("SELECT * FROM products WHERE Category = 'Acoustic ' ORDER BY RAND()");
However this doesn't work. I get the following error:Call to undefined function prepare()
I still would like to get my values as:<?php echo $row_AcousticDB['what ever']; ?>
Can somebody point me into the right direction?
How about this?
$category = "Acoustic";
$sql = "SELECT * FROM products WHERE Category = ? ORDER BY RAND()";
$stmt = $DB->prepare($sql);
$stmt->bind_param('s', $category);
$stmt->execute();
$row_AcousticDB = $stmt->get_result(); // altenative: $stmt->bind_result($row_AcousticDB);
$row_AcousticDB->fetch_array(MYSQLI_ASSOC)
If you let the user enter any data (in text boxes on website) or you pull anything out of database for use (risk of second order injection) make sure you sanitize it (cleanse it of any nasty tags like < or >) by using htmlspecialchars($category) or htmlentities($category).
With this method implemented into your code, you will be reasonably safe from SQL Injection :)
Try to make this variable global: Put this on the upper part of your script global $acousticDB; or else you may try this $acoustic='';

Get subject from Table in PHP

OK So I'm trying to access a table called emg_quote I have the Quote ID so Im trying to get the Column Subject from the same row as this ID but for some reason All I'm getting is the first row in the entire table? Can any one figure out what I'm doing wrong? Here is my coding:
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE ".$quoteid."";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Are you using a custom object to wrap the native API's?
Either way it doesn't look right to me. You don't seem to be using the result of the query.
i.e.
$result = $mysqli->query($query);
$row = $result->fetch_row();
You have few bad practices in your code.
A. You lie on $quoteid to give you the correct where syntax. ie: ID=123
This is an highly unsafe method, because the user can change the it to Some-Important-Details='bla'
To extract more details from this table or others.
B. You should ALWAYS escape characters when receiving data from user, otherwise you easily subjected to SQL-Injections. And believe me you don't want it.
you have to use the checking after where.
use you column name before your $quoteid variable
$row['quote_id'] = quoteTitle($row['quote_id']);
function quoteTitle($quoteid){
global $db;
$sql = "SELECT subject FROM emg_quote WHERE quoteid=".$quoteid." LIMIT 1 ";
$res = $db->query($sql);
$row = $db->fetch_row();
$output = $row['subject'];
return $output;
}
Remember : USE limit 1 when you search with primary key and you know that only 1 record will be searched. it reduce your processing time.
You might be missing the where column.
$sql = "SELECT subject FROM emg_quote WHERE quote_id=".$quoteid."";
^^^^^^^^
We also do not see weather something with your Db class is wrong.
You should in any case not directly put request variables into a database query.
$sql = "SELECT subject FROM emg_quote WHERE ID='".$quoteid."'";
You had not wrote your db fieldname in where condition

PHP Query failing, show error?

I have a query on my page that uses a GET variable to pull data from my table...
If I echo my GET var the data is there so im doing something wrong with my query, instead of or die can I show an error in the browser?
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!');
$sql = "SELECT * FROM persons WHERE id = $userID";
You must use double quotes to use variables inside the query string.
You can also do this:
$sql = "SELECT * FROM persons WHERE id = ".$userID;
What you should do is this (to protect yourself from sql injection):
$safeuid = $conn->prepare($userID);
$sql = "SELECT * FROM persons WHERE id = ".$safeuid;
You can always debug using this at the top of your php page:
ini_set('display_errors',1);
error_reporting(E_ALL);
Have you tried $q = $conn->query($sql) or die($conn->error()); ?
Yes you can, but you should only do it for debugging. Crackers can gain a lot of insight by purposefully feeding bad input and reading the error.
I'm assuming you're using MySQLi; the command is $conn->error(). So your line would be:
$q = $conn->query($sql) or die($conn->error());
Also, what you're doing wrong is you're using single quotes to define $sql. You need to use double quotes to write $userID into the string. So what you want is:
$sql = "SELECT * FROM persons WHERE id = $userID";
or
$sql = 'SELECT * FROM persons WHERE id = ' . $userID;
You need to use double quotes to evaluate variables within the string. That is,
$sql = 'SELECT * FROM persons WHERE id = $userID';
should be
$sql = "SELECT * FROM persons WHERE id = $userID";
Rather than removing the die you should make sure the query is always valid. In other words: validate the userID parameter. $_GET can contain anything the user wants to provide - it could be an array, it could be a string, it could be a string with a malicious payload that can drop your tables. So check it is an integer. If not, return a relevant message to the user.
Not a php expert but you might try:
// Get USER ID of person
$userID = $_GET['userID'];
// Get persons
$sql = 'SELECT * FROM persons WHERE id = $userID';
$q = $conn->query($sql) or die('failed!' . mysql_error());
The error should append to the end of your die message.

mysql_fetch_array error when using WHERE clause

Im using:
$query = "SELECT * FROM mydb WHERE condition = New ORDER BY id ASC";
but i get this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/mydb.php on line 84
however if i remove the where clause it works perfectly, can anyone point me in the right direction?
Is the Where clause not usable when doing a fetch array?
Thanks for any help.
edit: error message I've got:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition = 'New' ORDER BY id ASC'
always run all your queries this way (at least until you adopt some intelligent lib for this)
$query = "SELECT * FROM mydb WHERE condition = New ORDER BY id ASC";
$result = mysql_query($query) or trigger_error(mysql_error()." in ".$query);
just because not a single soul in the world can tell what's wrong with your query, but database itself. So, you have to ask it if there were any trouble. Not stackoverflow community (they have no idea anyway) but your db server. That's the point.
Note that you have to be able to watch errors occurred, either on-screen or in the error log.
After getting error message about syntax error you have to check syntax of the displayed query. If there are no visible errors, refer to http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html in case there are reserved word unescaped in your query. condition seems is. So
$query = "SELECT * FROM mydb WHERE `condition` = New ORDER BY id ASC";
will be solution
You appear to be missing quotes around the word "New".
$query = "SELECT * FROM mydb WHERE condition = 'New' ORDER BY id ASC";
Also, are you passing $query to mysql_fetch_array, or did you just not mention the mysql_query call in your question?
Since you have tried adding single quotes to the ('New'),
kindly ensure that the condition is a column in the table you are querying and
that mydb is a table in your database (and not your database name)!
You have to quote the string.
$query = "SELECT * FROM mydb WHERE `condition` = 'New' ORDER BY id ASC";
Edit:
condition is a reserved word.
Is New one of your columns or just a value?
Try this:
$query = "SELECT * FROM mydb WHERE condition = 'New' ORDER BY id ASC";
$query = "SELECT * FROM mydb WHERE condition = 'New' ORDER BY id ASC";
$result = mysql_query( $query );
while( $row = mysql_fetch_array( $result ) {
// use $row
}
Never assume that a query will work - expect errors and check for them before processing any results.
$query = 'SELECT * FROM `mydb` WHERE `condition` = "New" ORDER BY `id` ASC';
$result = mysql_query( $query );
if( !$result ){
// Query Failed. You can access the error details with mysql_error()
}elseif( mysql_num_rows( $result )==0 ){
// Query Returned No Results
}else{
while( $r = mysql_fetch_assoc( $result ) ){
// Do whatever you want with the row, which is $r
}
}

$_SESSION variable in mysql query?

Whenever I try a query like:
mysql_query("SELECT * FROM data WHERE `user`=$_SESSION['valid_user'] LIMIT 1");
it doesn't work. Why? I escaped the variable, then tried it without, and tried putting quotes around the variable. I know i can do:
$user = $_SESSION['valid_user'];
but shouldn't it work without? Thanks.
THE ANSWER:
PHP can't recognize $_SESSION['valid_user'] due to the single quotes. So either
use curly braces {} or take our the single quotes.
Thanks for helping me everyone.
PHP can't recognise variables inside a string that have square brackets and so on, you have to wrap it in curly brackets to get it to recognise it.
mysql_query("SELECT * FROM data WHERE user={$_SESSION['valid_user']} LIMIT 1");
However - You should always escape any data going into a SQL query, try the example below.
$validUser = mysql_real_escape_string($_SESSION['valid_user']);
mysql_query("SELECT * FROM data WHERE user='$validUser' LIMIT 1");
Arrays/objects must be included in strings slightly differently:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
or, you can drop out of the string and concatenate it in:
mysql_query("SELECT * FROM data WHERE `user`=" . $_SESSION['valid_user'] . " LIMIT 1");
Same but with PDO and bound parameters
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT 1');
$stmt->execute(array(':user'=>$_SESSION['valid_user']));
$row = $stmt->fetch();
Note: you can't make LIMIT 1 into a bound parameter because LIMIT is not part of the standard sql and PDO has issues with it, so it has to be bound like this
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT :limit');
$limit = 1;
$user = $_SESSION['valid_user'];
$stmt->bindParam(':user', $user, PDO::PARAM_STR);
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch();
or like this
$limit = 1;
$stmt = $pdo->prepare('SELECT * FROM data WHERE `user`=:user LIMIT '.(int)$limit);
$stmt->execute(array(':user'=>$_SESSION['valid_user']));
$row = $stmt->fetch();
this is the way that I was taught to do it, so I wanted to point it out
try this:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
also remember to put session_start on the top of the page
your array is in this context just part of a string and nothing else. To mark an expression as what it is you have to embrace it curly ;-) works only with double quoted strings, though.
mysql_query("SELECT * FROM data WHERE user={$_SESSION['valid_user']} LIMIT 1");
You need to use the string concatenation operator '.' before and after the variable.
mysql_query("SELECT * FROM data WHERE `user`=".$_SESSION['valid_user']." LIMIT 1");
Since you are using a double quoted string, you can also use {} around the variable instead of string concatenation:
mysql_query("SELECT * FROM data WHERE `user`={$_SESSION['valid_user']} LIMIT 1");
By the way, you probably should look into the mysqli (http://php.net/manual/en/book.mysqli.php) library, and be using mysqli::real_escape_string (http://www.php.net/manual/en/mysqli.real-escape-string.php) to ensure that any non-literal variable values are properly escaped.

Categories