PDO bindValue for table and column - php

Ok so I just found out that I can't use placeholders for table names and columns
$table = 'users';
$stmt = $db->prepare('SELECT * from ?');
$stmt->bindValue(1, $rable, ??);
So what is really an alternative to having dynamic table names?
$stmt = $db->prepare('SELECT * from '.$table);
This would be vulnerable. Is there an escape_string method for PDO? I went through the manual but didn't seem to catch one. All I found was quote but that doesn't work for tables and columns. Is there any way I can securely implement this functionality, or will I have to switch back to using mysqli?

For escape String
From the link:http://php.net/manual/en/pdo.prepare.php
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
Prepare values are only for fields.
Regarding dynamic table names
Append it table name to query as u did in second statement.
Example
$pdo = new PDO('mysql:host=localhost;dbname=site;',USER,PASS);
$query = $pdo->prepare("DESCRIBE :table");
$query->bindValue(':table', $table, PDO::PARAM_STR, strlen($table));
$query->execute();
while($field = $query->fetch(PDO::FETCH_NUM)){
var_dump($field);
//do something
}
unset($pdo);

Bindable Marks (?) or Bindable named Marks (:foo) couldn't appear as table-names or (pseudo-dynamic-) fieldnames. Both are limited to field-values.
You should avoid dynamic tables inside of your application. Just normalize your database to an more agile and intelligent structure.

If you use ticks, then you can simply replace ticks in the user input, and you should be fine:
$column = 'foo';
$table = 'bar';
$query = 'SELECT ' . $column . ' FROM ' . $table; // Insecure!
$query = 'SELECT `' . str_replace('`', '', $column) . '` FROM `' . str_replace('`', '', $table) . '`'; // Not insecure

Related

How to insert a PHP variable into an SQL query

I have an SQL query
qry1 =
"SELECT DISTINCT (forename + ' ' + surname) AS fullname
FROM users
ORDER BY fullname ASC";
This gets forename and surname from a table called users and concatenates them together, putting a space in the middle, and puts in ascending order.
I then put this into an array and loop through it to use in a select drop-down list.
This works, however, what I now want to do is compare the fullname with a column called username in another table called users.
I'm struggling with how to write the query though. So far I have...
$qry2
"SELECT username
FROM users
WHERE (forename + ' ' + surname) AS fullname
=" . $_POST['Visiting'];
Any advice on to what I am doing wrong?
Rather CONCAT the two columns together. Also remember to escape any variables before adding them to your query.
$qry2 =
"SELECT username AS fullname
FROM users
WHERE CONCAT(forename, ' ', surname)
='" . mysqli_real_escape_string($connection, $_POST['Visiting']) . "'";
Where $connection is your current db connection
I'm not sure that the use of the declared word 'AS' after 'WHERE' is correct in principle.
if you use MySQL, query should look like this:
SELECT [columns]
FROM [tables] [AS declareTableName]
WHERE [condition]
GROUP BY [declares|columns]
SORT BY [declares|columns]
But, i think your problem not in the query. Concatenating names in the query is incorrect. You must separate string with names in Back-end and than use it in query:
$names = explode(' ', $_POST['Visiting']);
This might work, assuming you use PDO:
$qry2 = "SELECT username FROM users
WHERE CONCAT(forename, ' ', surname) = '" . $conn->quote($_POST['Visiting']) . "'";
...but you should have a look at the possible vulnerabilities through SQL injections.
Without knowing which library you use for connecting to the MySQL database, it's impossible to give proper advise about which method you should use for escaping the user's input. quote is the PDO method for escaping, real-escape-string is the equivalent for MySQLi
You should really refer to using PDO.
When using PDO you can bind parameters to specified parts of your query. PDO also has built-in SQL-injection prevention, which is a great security measure that you won't have to deal with yourself. I hope this answers your question. See my example below.
Example:
// Create a new PDO object holding the connection details
$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Create a SQL query
$query = "SELECT username FROM users WHERE (forename + ' ' + surname) AS fullname = :visiting;";
// Prepare a PDO Statement with the query
$sth = $pdo->prepare($query);
// Create parameters to pass to the statement
$params = [
':visiting' => $_POST['Visiting']
]
// Execute the statement and pass the parameters
$sth->execute($params);
// Return all results
$results = $sth->fetchAll(PDO::FETCH_ASSOC);
If you have any other questions about PDO, please refer to the following:
Official PDO documentation:
http://php.net/manual/en/book.pdo.php
Documentation on how to bind variables:
http://php.net/manual/en/pdostatement.bindparam.php
You can use this construction (without "AS fullname" and with apostrophes around variable):
$qry2 "SELECT username FROM users WHERE (forename + ' ' + surname) = '" . $_POST['Visiting'] . "'";
But for better security (SQL injection) You should use the escaping of variable. For example this construction, if You use MySQL database:
$qry2 "SELECT username FROM users WHERE (forename + ' ' + surname) = '" . mysql_real_escape_string($_POST['Visiting']) . "'";

PHP "SHOW TABLES" MySQLi query not working

i'm trying to execute a prepared statement with php but it doesn't work. My prepared statement is like:
SHOW TABLES LIKE "italy_turin_mathematics"
and i do it like this:
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?_?_?")) {
$stmt->bind_param('sss', "italy", "turin", "mathematics");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
I'm sure it must return something, because with PHPMyAdmin it does, but with PHP it always skips the while loop, i think there is something wrong with the prepared statement query, maybe it needs to escape the underscore char?
How can i do it?
Your database architecture is utterly wrong.
There should be only one table contains all the data, for all the places and sciences.
And you have to query it usual way, without employing SHOW TABLES at all.
So, it have to be something like
$sql = "SELECT * FROM t WHERE country=? AND city=? and science=?";
$stm = $pdo->prepare($sql);
$stm->execute(array("italy", "turin", "mathematics"));
$data = $stm->fetchAll();
the above code is in PDO, as you have to use it instead of mysqli.
Splitting tables is a very bad idea, violating the very fundamental rules of relational databases. As you can see, it makes you to run such a strange query and will make your further code even worse.
if ($stmt = $this->mysqli->prepare("SHOW TABLES LIKE ?")) {
$country = "italy";
$city = "turin";
$course = "mathematics";
$stmt->bind_param('s', $country . "_" . $city . "_" . $course);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1);
while($stmt->fetch()) {
echo "Table: ".$column1;
}
}
As far as I know the code you had would result in a query looking as follows:
SHOW TABLES LIKE 'italy'_'turin'_'mathematics'
You cannot concatenate like that in mySQL, or any form of SQL I can think of.
SHOW TABLES LIKE ?_?_?
Should be:
SHOW TABLES LIKE CONCAT(?, '_', ?, '_', ?) --this gives an error, see below
And I fully agree with #your-common-sense's commentary that this is a terrible way to design a database and you will come to regret it in more ways than just this one messed up query.
edit:
MySQL does not seem to allow functions in a SHOW TABLES statement, so either you'll have to concatenate the table name to a single string in PHP, or you can use a query like:
SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLES
WHERE
table_schema = 'mydb' AND
table_name LIKE CONCAT(?, '_', ?, '_', ?);

not updating the sql database

i wrote the following code,but its not updating the database,,its a part of a script and it cease to work..cant find a way around it .. need suggestions
<?php
$link = mysql_connect('xxxxxxxx');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
echo $usernames;
$update = "INSERT sanjana SET $name ='$usernames'";
mysql_query($update, $link);
$update1 = "INSERT INTO sanjana (name)VALUES ($usernames)";
mysql_query($update1, $link);
?>
$update = "INSERT sanjana SET $name ='$usernames'";
this probably is meant as an UPDATE statement, so for an update it should be
$update = "UPDATE sanjana set name = '$usernames'";
I put name and not $name due to your second query and not seeing $name being defined anywhere. Be aware that this will change the value in the column name of every row in the sanjana table to the value of $usernames, normally a statement such as this gets limited by conditions, e.g. WHERE userid = 33
$update1 = "INSERT INTO sanjana (name) VALUES ($usernames)";
for an INSERT statement it needs to have the values quoted so
$update1 = "INSERT INTO sanjana (name) VALUES ('$usernames')";
Be wary that this way of putting variables directly into your query string makes you vulnerable to SQL injection, to combat this please use the PDO or mysqli extensions, they both protect you from injection by providing you with prepared statements ; plain old mysql_* is not recommended for use anymore.
using pdo you'd use prepared statements like this
<?php
// we got $usernames from wherever you define it
$pdo = new PDO('mysql:dbname=mydb;host=localhost','username','password');
// to insert
$statement = $pdo->prepare('INSERT INTO `sanjana` (name) VALUES (:name)');
// the following replaces :name with $usernames in a safe manner, defeating sql injection
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
// to update
$statement = $pdo->prepare('UPDATE `sanjan` SET `name` = :name');
$statement->bindParam(':name',$usernames);
$statement->execute(); // it is done
so as you can see protecting your code from malicious input is not hard and it even makes your SQL statements a lot easier to read. Did you notice that you didn't even need to quote your values in the SQL statement anymore? Prepared statements take care of that for you! One less way to have an error in your code.
Please do read up on it, it will save you headaches. PDO even has the advantage that it's database independent, making it easier to use another database with existing code.
The right update sql clause is like so:
UPDATE table
SET column = expression;
OR
UPDATE table
SET column = expression
WHERE predicates;
SQL: UPDATE Statement
Your query should be like this:
$update = "UPDATE sanjana SET $name ='$usernames'";
mysql_query($update, $link);
Of course you need to specify a row to update (id), other wise, the whole table will set column $name to $usernames.
UPDATE:
Because you are inserting a data in empty table, you should first execute $update1 query then execute $update query. UPDATE clause will make no change/insert on empty table.
Problem 1: use the correct "insert into" (create new record) vs. "update" (modify existing record)
Problem 2: It's good practice to create your SQL string before you call mysql_query(), so you can print it out for debugging
Problem 3: It's also good practice to detect errors
EXAMPLE:
<?php
$link = mysql_connect('xxxxxxxx')
or die('Could not connect: ' . mysql_error());
mysql_select_db("xxx", $link);
$usernames='aneeshxx';
$sql = "INSERT INTO sanjana (name) VALUES ('" . $usernames + ")";
echo "sql: " . $sql . "...<br/>\n";
mysql_query($sql, $link)
or die(mysql_error());
You have INSERT keyword for your update SQL, this should be changed to UPDATE:
$update = "UPDATE sanjana SET $name ='$usernames'";

Parameterised IN Clause in prepared statement using MySql,PHP and ADODB

I am writing some SQL and using AdoDb to connect to my database and run the queries and so on. I am using parametrized queries and have run into a snag.
Is their a way to pass an array of values to an in_clause in AdoDb/MySql for parametrization.
My problem is that if I pass a prepared string as the parameter i.e. 'test','test2','test3' it does not work as the library or database auto escapes it and adds external quotes at the start and end so all the internal quotes are then auto escaped thus the query returns nothing as it looks for '\'test\',\'test2\',\'test3\'' as opposed to what I fed it.
UPDATED WITH ANOTHER POSSIBLE METHOD TO ACCOMPLISH THIS
<?php
$in_clause = implode(",", $first_names);
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
FIND_IN_SET(mytable_fname," . $DB->Param('first_names') . ")"
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,array($in_clause));
?>
I would do it this way (as I was googling for a while and google came up with nothing useful):
$count = count($first_names);
$in_params = trim(str_repeat('?, ', $count), ', ');
$query = "
SELECT
mytable_id_pk
FROM
mytable
WHERE
mytable_fname IN ({$in_params});";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt, $first_names);
This should do it...
First a few tips:
Please read carefully the AdoDB documentation on prepared statements.
Never include ; in SQL query strings.
You can try something like this:
$question_marks = substr(str_repeat('?,', count($first_names)), 0, -1);
$query = "SELECT mytable_id_pk FROM mytable WHERE mytable_fname IN (" . $question_marks . ")";
$stmt = $DB->Prepare($query);
$result = $DB->Execute($stmt,$first_names);
WARNING: I haven't tested this (not having a mySQL installation here).

Using mysql_real_escape_string in IN clause

mysql_real_escape_string adds slashes to the values in IN clause and hence no values are returned. How can I send array values that are escaped using mysql_real_escape_string() in IN clause?
Here is my code:
$names_array = array('dave','smith');
$names = mysql_real_escape_string("'". implode("', '", $names_array) ."'");
$sql = "SELECT * FROM user WHERE user_name IN ($names)";
$results = mysql_query($sql);
Query after mysql_real_escape_string changes like this:
SELECT * FROM user WHERE user_name IN (\'dave\', \'smith\')
I don't want these slashes here in IN clause. Also I don't want the values directly substituted in IN clause.
Thanks in Advance.
This might do it.
$names = "'". implode("', '", array_map('mysql_real_escape_string', $names_array)). "'";
Don't use mysql_real_escape_string; don't use the mysql_* functions directly at all; use ADODB or somesuch; don't concatenate your queries in this way, use placeholders (?) and prepared statements. Your code should look similar to this:
include('/path/to/adodb.inc.php');
$DB = NewADOConnection('mysql');
$DB->Connect($server, $user, $pwd, $db);
# M'soft style data retrieval with binds
$rs = $DB->Execute("select * from user where user_names in ?",array(array('dave','smith')));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}

Categories