Converting query to parametrised query [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a query on my site and have recently been hacked because of it.
I have spent a good 2 hours looking how to convert this query so it is secure and have not got anywhere.
If anyone don't mind, could you please convert this one for me just so I can see what to do on the rest?
$camera_id = $_GET['camera_id'];
$cameras = mysqli_query($conn, "SELECT * FROM cameras WHERE id = $camera_id");
$camera = mysqli_fetch_array($cameras);

Try something like this.
$camera_id = $_GET['camera_id'];
$cameras = mysqli_prepare($conn, "SELECT * FROM cameras WHERE id = ?");
mysqli_stmt_bind_param($cameras, $camera_id);
$cameras->execute();
While you are making the switch, switch straight away to PDO. It's far better than mysqli
$db = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM cameras WHERE id = :camera_id");
$stmt->execute(array(":camera_id"=>$camera_id));
$result = $stmt->fetchAll();
or instead of fetchAll()
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'].' '.$row['field2']; //etc...
}
As you can see this is more readable. And if you later decide eto switch to postgresql the change is real easy.

This is using PDO and assumes that the camera id is a number (if it can contain non-numerical values swap the PARAM_INT for a PARAM_STR. The basic premise is that you separate the query from the variables and you bind the value of the desired item to a variable. Also note that you would need to alter the variables in the new PDO declaration to suit your own database. Note also that fetchAll() provides an associative array of the returned results - there are a number of other fetch() methods possible to give different outcomes - look for the official documentation.
$camera_id = $_GET['camera_id'];
$conn = new PDO('mysql:host=localhost;dbname=db', 'username', 'password');
$sql = "SELECT * from cameras where id = :cameraId";
$q = $conn->prepare($sql);
$q -> bindValue(":cameraId" , $camera_id, PDO::PARAM_INT);
$q->execute();
$cameraRows = $q->fetchAll();
foreach($cameraRows as $cameraRow){
$CID= $cameraRow["camera_id"];
//.... rest of the code
}

Related

Propper conversion of PHP and SQL data types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
A seemingly minor problem are bothering me, something that should have a simple solution. I am currently running a server and a database, the database which contains data that I want to use in a PHP request on a website. I have created a function in PHP that does the following:
function getUserID($val){
include("config.php");
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$sql = "SELECT userid FROM users WHERE username=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $val);
$stmt->execute();
$result = $stmt->get_result();
if(getUserExist($val)){
$rowdata = mysqli_fetch_assoc($result);
$conn->close();
return $rowdata['userid'];
}
}
This works just fine.. HOWEVER. The returned data type, which is supposed to be an Integer ( 1, 2, 3, 4... etc. ), returns a value similar to an JSON object or int(1), depending on how I write it.
array(1) { ["userid"]=> int(4) }
I have tried:
$rowdata['userid']
$rowdata
How do I make the function return purely the integer value? When it is added to the database with following code-snippet:
...
$stmt = $conn->prepare("INSERT INTO users (user1, user2, user3) VALUES (?, ?, ?)");
$stmt->bind_param("isi", $user1, $user2, $user3);
$user1 = $_POST[getUserID($username)];
$user2 = $_POST['val2'];
$user3 = $_POST['val3'];
$stmt->execute();
$stmt->close();
}
$conn->close();
As mentioned, it retrieves data just fine, it is just the value that acts in an odd way. When this code is executed, $user1 or rather the final value within database has the value of NULL. (database accepts only integers in that slot).
It looks to me as if the problem does not lie in getUserID(), but in this line:
$user1 = $_POST[getUserID($username)];
What you're doing here is not setting $user1 to the value of getUserID() - instead, you're setting it to "the element in the $_POST array which has a key of whatever getUserID() returns". And there are very few scenarios where that makes sense.
I'm assuming the line you want to replace it with is
$user1 = getUserID($username);

how to handel % in post method in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Im send a mysql query in php variable using post method having % value;
$Brand= 'SELECT BRAND_CODE FROM product WHERE STATUS='1' AND UNIT_CODE like '%"81"%'';
$Brand=$_POST['Brand'];
echo $Brand;
and result is
SELECT BRAND_CODE FROM product WHERE STATUS='1' AND UNIT_CODE like '%
How can I get the complete string using this
$Brand= "SELECT BRAND_CODE FROM product WHERE STATUS='1' AND UNIT_CODE like '%81%'";
$Brand=$_POST['Brand'];
echo $Brand;
And the result will be like:
SELECT BRAND_CODE FROM product WHERE STATUS='1' AND UNIT_CODE like '%81%'
You should be using a prepared statement any time variables are involved and especially when they come from $_GET/$_POST requests to avoid MySQL injection.
Although your request isn't super-clear I'm taking a stab in the dark and assuming that you're trying to at least run a different or modified version of that query based on some sort of user interaction - while I haven't tested the below code it should serve as a good starting point for how you can modify queries safely using prepared statements and PDO.
You can view the following link for reference https://phpdelusions.net/pdo
<?php
// Configure the below based on your DB
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// Leave this as-is
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// Attempt connection here accessed via $pdo below
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// Get your brand variable from post request
$brand = "%{$_POST['Brand']}%";
// Prepare an SQL statement with your status and brand variables
$stmt = $pdo->prepare("SELECT BRAND_CODE FROM product WHERE status = ? AND UNIT_CODE LIKE ?");
// Execute the above statement, bind variables here to avoid MySQL injection
$stmt->execute([ 1, $brand ]);
// Retrieve your results (if any)
$results = $stmt->fetchAll();
// Clean up, checks and do what you will with the results..

Use WHERE IN with PDO PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to build a shopping cart using PHP, I get a list of IDs from the products added to the basket, I then want to query my database with these IDS using a WHERE IN SQL statement to get the details of the items added to the basket.
At the moment my query just comes back with false.
if(isset($_SESSION["cart"])) {
foreach ($_SESSION["cart"] as $id => $value) {
$ids .= $id . ',';
$count += $value['quantity'];
}
$query = $database->find_item_db($ids);
EDIT I have now changed my function to use the PDO syntax.
function find_item_db($product_code) {
$query = substr($product_code, 0,-1);
$product_codes = explode(",", $query);
$product_code_new = "(".implode("', '", $product_codes).")";
//we need to get product name and price from database.
$sql = "SELECT * FROM `Sweets` WHERE `Sweet_ID` IN :id";
$statement = $this->connection->prepare($sql);
$statement->bindParam(':id', $product_code_new);
$statement->execute();
return $done = $statement->fetchAll();
}
However this is still returning nothing, I get this error in my logs.
/var/www/html/sweetshop/partials/categories-nav.php(32): Database_Functions->find_item_db('1,10,6,23,')\n#2 /var/www/html/sweetshop/category.php(17): include('/var/www/html/s...')\n#3 {main}\n thrown in /var/www/html/sweetshop/classes/class-database-functions.php on line 139, referer: http://localhost/sweetshop/category.php?type=Chocolate
I know my connection works fine as all my other queries work perfectly.
1. Incorrect syntax
If $ids is something like:
$ids = "1,2,3,4,5";
Then the query is:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN (1,2,3,4,5)
Which is incorrect because each value needs to be wrapped in single quotes:
function find_item_db($product_code){
$query = substr($product_code, 0,-1);
//Wrap each product id
$product_codes = explode("," $product_code);
$product_codes = "'".implode("', '", $product_codes)."'";
//.......
}
That way the query will read:
SELECT * FROM `Sweets` WHERE `Sweet_ID` IN ('1', '2', '3', '4', '5')`
2. Mixing SQL APIs
mysqli_* syntax and PDO syntax are not interchangeable. bind_param() is for PDO, however your query is using mysqli.
When you are using $statement->bind_param(':id', $new);, what are you binding? There is no :id value in the query, and therefore the line is unnecessary as well as incorrect SQL query format!

strip_tags() on MySQLi Query and PHP Function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying hard to learn how to create functions, and I don't know what I'm doing wrong here. Could someone explain it to me please?
I'm not using strip_tags(), why it's getting me this error?
I don't need it to return, I just to need to update database if
$xp is bigger than $row['basenumber']
Thank you!
$xp = $row['userxp'];
$lvl = $row['userlevel'];
contXP($xp, $lvl);
function:
function contXP ($xp, $lvl) {
$query = "SELECT
number, basenumber
FROM levels
WHERE number = '$lvl'";
$result = $conn ->query($query);
if (!$result) die ($conn->error);
$rows = $result->num_rows;
while ($row = $result->fetch_array (MYSQLI_ASSOC));
if ($xp >= $row['basenumber'])
{
// up level
$level = "UPDATE users
SET userlevel = userlevel + 1
WHERE idusers = '$iduser';";
$re_level = $conn ->query($level);
if (!$re_level) die ($conn->error);
$re_rows = $re_level->num_rows;
$re_row = $re_level->fetch_array (MYSQLI_ASSOC);
$re_level->close(); //close query
}
$result->close(); //close query
}
result:
Warning: strip_tags() expects parameter 1 to be string, array given in on line 32
strilp_tags() is definitely somewhere in your code to throw the error. Try posting all the codes involved so we can find out where your problem is coming from.

how to use php variables make query for sqlite3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
<?php
/**
* Simple example of extending the SQLite3 class and changing the __construct
* parameters, then using the open method to initialize the DB.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('wifin.db');
}
}
$db = new MyDB();
$mac = 'test';
$ssid = $_POST['ssid'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];
$db->exec("INSERT INTO wifinTb (mac,ssid,lat,lon) VALUES ($mac,$ssid,$lat,$lon)");
$result = $db->query('SELECT * FROM wifinTb WHERE mac=$mac');
var_dump($result->fetchArray());
?>
i'm not sure how to use variables in php5, $mac should be a string, when i directly use mac=$mac, it return me bool(false), which means can't find, but when i use mac='test', it gives me result.
Never ever use string concatenation or replacement to put values into SQL statements; this will give you formatting problems (as you've seen) and allow SQL injection attacks.
Instead, use parameters:
$stmt = $db->prepare('INSERT INTO wifinTb(mac,ssid,lat,lon) VALUES (?,?,?,?)');
$stmt->bindValue(1, 'test');
$stmt->bindValue(2, $_POST['ssid']);
$stmt->bindValue(3, $_POST['lat']);
$stmt->bindValue(4, $_POST['lon']);
$stmt->execute();
$stmt = $db->prepare('SELECT * FROM wifinTb WHERE mac = :mac');
$stmt->bindValue(':mac', $mac);
$result = $stmt->execute();
What you initialize $mac with 'test', is what you are doing is assigning a string (PHP recognizes anything inside '' or "" as a string) to $mac. The value of this string is test. So you still need to surround the value in the query with '':
$db->exec("INSERT INTO wifinTb (mac,ssid,lat,lon) VALUES ('$mac','$ssid','$lat','$lon')");
$result = $db->query('SELECT * FROM wifinTb WHERE mac=$mac');
Is currently being seen as one long string. You could get around this quickly by changing it to:
$result = $db->query("SELECT * FROM wifinTb WHERE mac='" . $mac . "'");
However, you'd be better reading up on PDO or mysqli bind functions rather than injecting like that.
Hope that helps?

Categories