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

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..

Related

Is it possible to pass a "PHP" variable that is passed by an URL as comparison element for a SQL query? [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I've set a local server using PHPMyAdmin, and I'm presenting some dynamic data that is stored in that server using some PHP, HTML and SQL. The problem is that whenever I pass a variable that is stored using $variable = mysqli_real_escape_string($conn, $_GET["variable"]); and then I use that variable in a SQL query similar to this one $sql = 'SELECT * FROM assets WHERE variable="$variable";. The array that is generated is empty.
When I do a print_r($variable);, I get the variable that the code is expecting, so I'm not sure why the query sends an empty array. Then, when I hardcode the SQL query with the value of print_r($variable), the correct array is obtained from the query.
Code in PHP that is not working
$variable = mysqli_real_escape_string($conn, $_GET["variable"]);
print_r($_GET["location"]);
// make SQL
$sql = 'SELECT * FROM assets WHERE variable="$variable"';
Where $conn = mysql_connect('localhost', 'user', 'password', 'table');
The connection is correct though
then for example when I hardcode it using the result I get from
print_r($_GET["variable"]); prints N1 on the screen
This PHP is working, but it won't be dynamic
$sql = 'SELECT * FROM assets WHERE variable="N1';
I'm expecting to see all the results were the field variable = to a $_GET["variable"], where $_GET["variable"] is stored in $variable, but all I'm getting is an empty string.
You could use a prepared statement and binding param (for this you don't need the real string escape id done by the msqli prepared and binding)
$conn= new mysqli('localhost', 'user', 'password', 'your_db');
$myVar = $_GET["location"];
$sql = 'SELECT * FROM assets WHERE variable=?';
$query = $conn->prepare( $sql);
$query->bind_param('s',$myVar);
$result = $query->execute();
Try this code may be solve issues.
$conn= new mysqli("localhost","my_user", "my_password", "world");
$sql = 'SELECT * FROM assets WHERE variable='.$_POST["variable"];
mysqli_query($conn,$sql);

API doesn't allow text

I've just created a simple API for a CAD/MDT I'm working on, I've managed to get it to show the correct information when I do /citations/userid/1. This will then display all the correct values from the SQL database however, if I do /citations/issued_by/kevingorman1000 it will just throw an error. I can't tell what the error is as I'm using Slim php and can't seem to get the errors to display.
Any ideas why it isn't working ? I've added my code below..
$app->get('/citation/issuedby/{issued_by}', function(Request $request, Response $response){
$issued_by = $request->getAttribute('issued_by');
$sql = "SELECT * FROM ncic_citations WHERE issuedby = $issuedby";
try{
// Get DB Object
$db = new db();
// Call Connection to DB
$db = $db->connect();
$stmt = $db->query($sql);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($issby);
} catch(PDOExecption $e) {
echo '{"error"} : {"text": '.$e->getMessage().'}';
}});
Any ideas why this is the case? Does it only allow getting via number or do I need too do something else? First time using this and kinda new to PHP as well.
Thanks for any help.
Your problem is called SQL injection. You can solve it by using prepared statements. Never escape the values with quotes or anything else, as others might have suggested.
$sql = "SELECT * FROM ncic_citations WHERE issuedby = ? ";
$stmt = $db->prepare($sql);
$stmt->execute([$issuedby]);
$issby = $stmt->fetchAll(PDO::FETCH_OBJ);
For a good tutorial on PDO and prepared statements I recommend: https://phpdelusions.net/pdo
It's because SQL error (missing quotes around string).
You try to send query
$sql = "SELECT * FROM ncic_citations WHERE issuedby = kevingorman1000";
Correct query has to be
$sql = "SELECT * FROM ncic_citations WHERE issuedby = 'kevingorman1000'";

Need help some code that isn't working [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 4 years ago.
Improve this question
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$follow = strip_tags($_POST["follow"]);
$follow = addslashes($follow);
$follow = mysqli_real_escape_string($conn, $follow);
$sesid = $_SESSION["id"];
$rowid = $row['id'];
$followers = $conn->query("INSERT INTO followers (forid, fromid) VALUES ('$rowid', '$sesid'");
echo "<h3><center>Sucessfully followed!</center></h3>";
}
It doesn't seem to work. It doesn't throw any errors. I'm a new(er) PHP developer. Thank you!
STOP this madness... Do not insert values into a query, that's how bad things happen.
Also, add some error checking here and there, it's impossible to know what's wrong with the piece of code (or is it?):
Try something more like this:
$conn = new mysqli('localhost', 'root', 'password', 'db_name');
if ($conn->connect_errno) {
throw new Exception('Connection Error' . $conn->connect_err);
}
Now let's deal with the post data:
if(isset($_POST)) {
$follow = $_POST["follow"];
$sesid = $_SESSION["id"];
$rowid = $row['id']; // don't know where this is coming from
if($stmt = $conn->prepare("INSERT INTO followers (forid, fromid) VALUES (?, ?)") {
$stmt->bind_param('si', $follow, $sesid);
if(!$stmt->execute()) {
throw new Exception('Error! Could not execute query.');
}
$stmt->close();
} else {
throw new Exception('Could not prepare query!');
}
} else {
// Add a error checking here
throw new Exception('No post data');
}
Prepared statements will help you avoid anyone trying to insert undesired content into your query (SQL injection).
The way it works,
Prepare the query ($conn->prepare())
Note here that there are simple ? where the values would otherwise be. That's for our next step.
Bind the parameters of your query with $stmt->bind_param(). This will tell PHP where each value should go, starting at the second parameter position.
The documentation for the bind_param function: bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
A little explanation for the first param:
s - stands for string (the $follow, I assume is a string)
i - stands for integer. The session ID
Then, finally, execute the query ($stmt->execute()). That will do the hard work of adding the values to your database.
Explicitly close the connection to your database ($conn->close());
Read more on PHP's official documentation.

Converting query to parametrised query [closed]

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
}

PDO doesnt return data from mysql to jQuery AJAX [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm working on a web application to maintain the administration of a restaurant, wich the functions such as:
Show a list of all the orders, and the specific data from that when clicking on one
Make or delete a order
Maintain the finance's
etc...
First i was used to using the mysqli extension, and was using functions like this (with the return statement):
function get_all_data_by_order_id($order_id) {
$query = "SELECT customers.first_name,
customers.last_name,
customers.email_adress,
customers.customer_info,
orders.order_info,
orders.total_price,
orders.location,
orders.created
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
WHERE orders.id = {$order_id}";
return $this->query($query);
}
And now i wanted to try it with PDO so i could use prepared statement easier.
I've got this php file:
try {
$connection = new PDO('mysql:host=localhost;dbname=broodjes-service', 'root', 'password');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_GET['order_id'])) {
$order_id = $_GET['order_id'];
$query = "SELECT customers.first_name,
customers.last_name,
customers.email_adress,
customers.customer_info,
orders.order_info,
orders.total_price,
orders.location,
orders.created
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
WHERE orders.id = :order_id";
$statement = $connection->prepare($query);
$statement->bindParam(":order_id", $order_id, PDO::PARAM_INT);
$statement->execute();
$order_data = $statement->fetch(PDO::FETCH_ASSOC);
$orderObject = array();
$orderObject['header'] = mysqli_fetch_array($order_data);
echo json_encode($orderObject);
$connection = null;
}
} catch (PDOException $e) {
echo $e->getMessage();
die();
}
Wich is getting called by this piece of javascript to make it look like the page is'nt reloading:
function select_order(order) {
var item = $(order);
if (!item.hasClass("selectedRow")) {
if (!selectedOrderInformation.is(":visible")) {
switchScreen(selectedOrderInformation, financeOverview);
}
item.parent().find(".selectedRow").removeClass("selectedRow");
item.addClass("selectedRow");
selectedOrderInformation.html("loading......");
$.ajax({
url: "includes/functions/select-order.php",
type: "get",
dataType: 'json',
data: {order_id: item.attr("data-order-index")},
success: function (data) {
selectedOrderInformation.html('<h3>' + data['header']['first_name'] + '</h3>'); }
});
} else {
console.log("DEBUG: Row is already selected");
}
}
Problem
When i try to select a order inside the list theyre in, nothing is happening. The screen stays on the 'loading...' screen. It seems like it is'nt even executing the query.
Question
How can i make it so that my javascript file actually reacts on the php file by deploying data from the mysql database?
Don't mix PDO and MySQLi
Since you only want to select one row, use fetch() or fetchAll()[0]
Recommended way:
$statement->execute();
$orderObject = array();
$orderObject['header'] = $statement->fetch(); //or: $statement->fetchAll()[0]
echo json_encode($orderObject);

Categories