Searching with multiple variables PHP/Mysql - php

I'm trying to create a search where the column and value are both variables using prepared statements. The query is where I need help.
$column=$_POST['filter'][0][columnName];
$value = trim($_POST['filter'][0][value]);
$stmt = $mysql->prepare("select * from TABLE WHERE $column like '%$value%'");
I want to be able to specify different column and value pairs to use in conjunction with eachother- so that i can search column one for one value and also column two for another value.
thanks!

I don't think PHP's mysql library has prepared statements. Is your $mysql variable actually a mysqli or pdo connection object?
With mysqli, your code would look like this:
$dbconnection = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$stmt = $dbconnection->prepare("select * from TABLE WHERE $column like '%?%'");
$stmt->bind_param('s',$value);
There's no way to bind a parameter for a column name, which means that you're stuck inserting $column directly into your query. Doing that with any value the user passed you in POST is a bit of a security hole. Since it's constrained to be the same as one of your column names, I'd suggest validating it first to make sure it's not set to something different.

Related

use PHP to insert multiple columns to MySQL from browser

This should be pretty simple, I am just new to PHP...
If I have this..
http://localhost/write_data.php?value=99 and inside the write_data.php is this...
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
$dbselect = mysqli_select_db($dbconnect, "plantData_001");
// Prepare the SQL statement
$sqlAddress = "INSERT INTO sensorData (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysqli_query($dbconnect, $sqlAddress);
everything works fine and 99 is appended into the data table. But how do I add multiple values? I have a column named id that needs to be called like this...
http://localhost/write_data.php?id=1234567;value=99
Do you want to insert multiple values?
You should accept the new way to pass values by script query param.
Something like that: http://localhost/write_data.php?values=99,100,88,20,44.
Then you should use i.e. explode function to split values into array and would be able to insert multiple rows.
BUT - you should implement also the functionality to secure your input from query param. Please, read about SQL injection and MySQLi - https://stackoverflow.com/a/16282269/8890700

Safe way to write a PDO query

Which of these two is the safe method to write a query?
$stmt = $pdo->prepare("UPDATE tableName SET fieldName = 0");
OR
$stmt = $pdo->prepare("UPDATE tableName SET fieldName = :parameter");
$stmt-> bindValue(':parameter', 0);
I know the 2nd method is way best and I use it whenever I use a $variable in bindValue. But here, I need to use a known integer 0. So, the first process seemed easier as I did not had to write another bindValue statement. But, is it safe?
Looking at your questions I'd say that you'll definitely benefit from reading the PDO tutorial I wrote, which says:
There are two ways to run a query in PDO. If no variables are going to be used in the query, you can use the PDO::query() method.
and
if at least one variable is going to be used in the query, you have to substitute it with a placeholder, then prepare your query, and then execute it, passing variables separately.
So now you can tell that for this particular query you can use the query() method instead of prepare/execute
$stmt = $pdo->query("UPDATE tableName SET fieldName = 0");
as there is no variables to be used and this no danger at all

mysqli prepared statement with fetch_assoc

my goal here is to be able to get a variable (with php) and use it in a prepared statement (with mysqli), and then fetch_assoc. For some reason this code will not work (no errors). I've rtm and I haven't found anything combining fetch_assoc with prepared statements, so I'm not sure if it's even possible. Any help to get this working is appreciated, here's my code currently.
$where = $_GET['section'];
$mysqli = mysqli_connect("localhost", "root", "","test");
if($stmt = mysqli_prepare($mysqli,"SELECT title, img, active, price FROM ? ORDER by ID limit 5 ")){
mysqli_stmt_bind_param($stmt, 's', $where);
mysqli_stmt_execute($mysqli);
mysqli_stmt_fetch($mysqli);
while($row = mysqli_fetch_assoc($stmt)){
if($row['active']=="yes"){
echo 'the rest of my stuff goes here';
From the PHP website page for mysqli->prepare (with emphasis added to the most relevant part):
Note:
The markers are legal only in certain places in SQL statements. For
example, they are allowed in the VALUES() list of an INSERT statement
(to specify column values for a row), or in a comparison with a column
in a WHERE clause to specify a comparison value.
However, they are not allowed for identifiers (such as table or column
names), in the select list that names the columns to be returned by a
SELECT statement), or to specify both operands of a binary operator
such as the = equal sign. The latter restriction is necessary because
it would be impossible to determine the parameter type. In general,
parameters are legal only in Data Manipulation Language (DML)
statements, and not in Data Definition Language (DDL) statements.
Assuming you can get past that problem, your use of mysqli is a little confused. You correctly bind your parameters and execute, but you've mixed up two different ways of getting at your results. Either
Use mysqli_stmt_get_result to fetch the result set and then use mysqli_fetch_assoc on that, or
Bind your results with mysqli_stmt_bind_result, and then use mysqli_stmt_fetch to fetch the next set of results into your bound variables. (Usually you'd iterate over the results using something like while(mysqli_stmt_fetch($stmt)){ //do stuff here }
Another way style, we can write it below:
$mysqli=new mysqli("host","user","pass","db");
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $variable);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()){
....
}

Using PHP variables inside MYSQL stored queries

I searched before posting this but didn't find an answer to my question.
I have a table in a database which stores queries such as (with the php variable stored in the database):
select * from accounts where type = 'client'
select * from accounts where user_id = $userid
select * from accounts where name = '$name'
I assumed that when I pulled that particular query from the database that PHP would recognized the variable and replace it but it treats it as regular text.
Is there a way to have PHP replace the $__ with an actual variable that exists? I think maybe the eval() function perhaps??
What you might try is using it as a prepared statement. So instead, if your database stored queries looked like this:
select * from accounts where type = 'client'
select * from accounts where user_id = ?
select * from accounts where name = ?
and you use PDO prepared statements like this:
$pdo = new PDO($dsn, $user, $pass);
$statement = $pdo->prepare($secondOfTheAboveQueries);
$statement->execute(array($userId));
$account = $statement->fetch();
You could also use prepared queries with named variables like user_id = :userid instead of questions marks if you have to process a few statements at a time with various variables.
You may also want to consider stored procedures which work similarly. An explanation for both can be found here:
http://php.net/manual/en/pdo.prepared-statements.php
Assuming that you pull the query from a database:
$string = ''; // Assign the real userID
while ($fetch = mysql_fetch_array($query)) {
$newQuery = str_replace('$userid', $string, $fetch['your_row_name']);
}
I'm not sure if this will work, but this is what i would try first...
sprint seems to work well. instead of storing them as $variable, I can use %s, etc.

How do you connect/retrieve data from a MYSQL database using objects in PHP?

Generally I connect and retrieve data using the standard way (error checking removed for simplicity):
$db = mysql_select_db("dbname", mysql_connect("host","username","passord"));
$items = mysql_query("SELECT * FROM $db");
while($item = mysql_fetch_array($items)) {
my_function($item[rowname]);
}
Where my_function does some useful things witht that particular row.
What is the equivalent code using objects?
Since version 5.1, PHP is shipped with the PDO driver, which gives a class for prepared statements.
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password); //connect to the database
//each :keyword represents a parameter or value to be bound later
$query= $dbh->prepare('SELECT * FROM users WHERE id = :id AND password = :pass');
# Variables are set here.
$query->bindParam(':id', $id); // this is a pass by reference
$query->bindValue(':pass', $pass); // this is a pass by value
$query->execute(); // query is run
// to get all the data at once
$res = $query->fetchall();
print_r($res);
see PDO driver at php.net
Note that this way (with prepared statements) will automatically escape all that needs to be and is one of the safest ways to execute mysql queries, as long as you use binbParam or bindValue.
There is also the mysqli extension to do a similar task, but I personally find PDO to be cleaner.
What going this whole way around and using all these steps gives you is possibly a better solution than anything else when it comes to PHP.
You can then use $query->fetchobject to retrieve your data as an object.
You can use the mysql_fetch_object()
http://is2.php.net/manual/en/function.mysql-fetch-object.php

Categories