Can i run functions after SELECT * FROM db WHERE in php? - php

I want to use a function after WHERE
like this it works
$sql = "SELECT * FROM Prodotti WHERE Id=10";
what if i want the id to be in the URL link?
the link example is this: https://www.try.org/product.php?signup=98
this way it's not working
$sql = "SELECT * FROM Prodotti WHERE strpos($fullUrl, signup=Id)";

You can get the id by using the $_GET superglobal:
$id = (int) $_GET['signup']; // (int) makes sure it is an integer and no string
Now in order to make it work within your query you first need to make the input secure.
You can make an input secure by using mysqli_real_escape_string but since you need an integer and not a string it is better to use a prepared statement.
In your query you can than do
$sql = "SELECT * FROM `Prodotti` WHERE `Id` = $id";
Use backticks around table and column names to prevent mysql reserved word error.
Example of prepared statement:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$id = (int) $_GET['signup'];
if ($stmt = $mysqli->prepare("SELECT * FROM `Prodotti` WHERE `Id` = ?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $id);// i for integer s for string
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
// Do something with the fetched data
/* close statement */
$stmt->close();
}

You can get the signup parameter from the url like this:
$signup = $_GET['signup'];
and then use it in your query:
$sql = "SELECT * FROM Prodotti WHERE Id = '$signup'";
but this is not secure, i suggest you also google for "php mysql prepared statements"

Related

How to authenticate users with credentials in MySQL database

On my form page, I have two textboxes with the names name and password.
When the user hits submit, it sends that data into two columns in a MySQL database named 'name' and 'password'.
After the data is recorded (which is the part I understand and don't need help with), I want the user to be at the sign-in page and type in his/her name and password and only be allowed into the site if the name and password data already exist in the database (part that I don't understand).
Would I use the following query :
SELECT * FROM tablename WHERE name & password = "'$_POST[name]', $_POST[password]'
You should use AND or && instead of just a single ampersand (&), and separate the variables to be binded accordingly to their column name.
You should also consider sanitizing your variables before using them to your queries. You can use *_real_escape_string() to prevent SQL injections.
$name = mysql_real_escape_string($_POST["name"]);
$password = mysql_real_escape_string($_POST["password"]);
"SELECT * FROM tablename WHERE name = '".$name."' AND password = '".$password."'"
But the best recommendation that I can give to you is to use prepared statement rather than the deprecated mysql_*
if($stmt = $con->prepare("SELECT * FROM tablename WHERE name = ? AND password = ?")){ /* PREPARE THE QUERY; $con SHOULD BE ESTABLISHED FIRST USING ALSO mysqli */
$stmt->bind_param("ss",$_POST["name"],$_POST["password"]); /* BIND THESE VARIABLES TO YOUR QUERY; s STANDS FOR STRINGS */
$stmt->execute(); /* EXECUTE THE QUERY */
$noofrows = $stmt->num_rows; /* STORE THE NUMBER OF ROW RESULTS */
$stmt->close(); /* CLOSE THE STATEMENT */
} /* CLOSE THE PREPARED STATEMENT */
For securing password, you could also look at password_hash().
Please Always use Prepared statement to execute SQL code with Variable coming from outside your code. Concatenating variable from user input into SQL code is dangerous ( consider SQL injection ), you could use prepared statement with mysqli or PDO ( recommended ).
Mysqli example:
$mysqli = new mysqli("example.com", "user", "password", "database");
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $user,$password);
$stmt->execute();
if($stmt->num_rows!=1) {
// check failed
}else{
// check success
}
PDO example (recommended )
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// error check you connection here
$query='select * from tablename where user =? AND password=?';
$stmt = $dbh->prepare($query);
$stmt->bindParam(1,$user);
$stmt->bindParam(2,$password);
$stmt->execute();
if($sth->fetchAll()) {
// check success
}else{
// check failure
}
Additionally you should also consider using some form of 1-way password encryption ( password hashing ) before storing it in your database and compare it to the hash( the most accepted way to do it is using Bcrypt).
You can use something like
SELECT count(*) FROM tablename WHERE name = "'.$_POST[name].' AND password = "'. $_POST[password].'"
You should expect count to be exactly 1 - indicating valid user, 0 - indicating invalid user
Anything greater than 1 should be invalid scenario indicating some kind of inconsistency in your database...
You should assign the variables to name & pass subsequently.
You can try this:
$con = mysqli_connect("localhost","YOURUSER","YOURPASS","YOURDB");
if (mysqli_connect_errno())
{
echo"The Connection was not established" . mysqli_connect_error();
$user
= mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['password']);
$query = "select * from tablename where user ='$user' AND password='$pass' ";
$run = mysqli_query($con,$query);
$check = mysqli_num_rows($run );
if($check == 0)
{
echo "<script> alert('Password or Email is wrong,try again!')</script>";
}
else
{
//get a session for user
$_SESSION['user']=$user;
// head to index.php; you can just put index.php if you like
echo"<script>window.open('index.php?login=Welcome to Admin Area!','_self')</script>";
}

Unable to concatenate sql in pdo statement [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> SQLSTATE[42000]: Syntax error or access violation: 1064 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 ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* i - corresponding variable has type integer
* d - corresponding variable has type double
* s - corresponding variable has type string
* b - corresponding variable is a blob and will be sent in packets
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";

Echo Mysqli query with POST variable?

want i want is to query my db with post variable in the query. It's not really working for me, does anyone know how to do it properly?
Here is what i have so far.
$query = "SELECT column FROM `table` WHERE 'name' = '$_POST[checkname]'";
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch($result);
echo $cod;
Any help is appreciated. Thanks guys.
Mysqli supports prepared statements, which protect against sql injection attacks. It would look like this:
/* Create a prepared statement */
$stmt = $mysqli -> prepare("SELECT column FROM table WHERE name=?");
/* Bind parameters */
$stmt -> bind_param("s", $_POST['checkname']);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $result;
Check the manual for more info.
A quick rundown, in response to the comment:
In $stmt->prepare("..."), you're forming your query, and you hold the place of any variables you intend to use with a "?"
In $stmt -> bind_param(...), you're binding the variables to their corresponding question mark. The first argument is the type, the following arguments are the variables. If you were using a string and an integer, inside the parenthesis it would look like "si", $stringVar, $intVar
In $stmt -> bind_result(...) you are stating what you are binding the results to. If the query was for a name and age, inside the parethesis would look like $name, age
In $stmt->fetch(), you're fetching the result. If it was multiple rows returned, you would do something like:
while($stmt->fetch()) {
//code here
}
Alternatively, you could use PDO. It would look something like this:
/* Create a prepared statement */
$stmt = $pdo->prepare("SELECT column FROM table WHERE name=:checkname");
/* Bind parameters */
$stmt->bindParam(':checkname', $_POST['checkname']);
/* Execute it */
$stmt->execute();
/* Fetch results */
$obj = $stmt->fetchObject();
echo $obj->column;
Check the manual for more info.
//it is apsulutly
// work
if(isset($_POST['checkname']))
{
$post = mysql_real_escape_string(trim($_POST[' checkname ']));
$query = "SELECT column FROM `table` WHERE name = '$post'";
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch_all($result);
echo implode($cod[0]);
echo implode($cod[1]);//For particular cell
}
it works, just try it out like this
following your code...
if(isset($_POST['checkname']))
{
//to avoid SQL injections
$post = mysql_real_escape_string(trim($_POST['checkname']));
$query = "SELECT column FROM `table` WHERE name = '$post'";``
$result = mysqli_query($db, $query) or die ("no query");
$cod = mysqli_fetch($result);
echo $cod;
}

Passing PHP variable to SQL query

$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query('UPDATE table SET field = field + ($userlogin)');
Is this the right way of getting userlogin from the post request and then inserting it to my SQL query?
Stop using outdated functions and use PDO instead.
$stmt = PDO::prepare('UPDATE table SET field = field + :field');
$stmt->execute(array('field' => $_POST["userlogin"]));
Read some information about PDO.
In short: it escapes your data for you, is quite consistent across databases and generally just easier.
you should use mysql_real_scape_string() just after connecting to database ...
so change your code to this :
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
$userlogin = mysql_real_escape_string($_POST["userlogin"]);
mysql_query("UPDATE table SET field = '$userlogin'");
Try like this.
$user = mysql_real_escape_string($_POST["userlogin"]);
mysql_connect("uritomyhost","myusername","password");
mysql_select_db('mydatabase');
mysql_query("UPDATE table SET field = value where user='$user'");
Try this
mysql_query("UPDATE table SET field = field + ('$user')");
However,
You might be updating all the fields in your table because you have no where in your UPDATE clause
Shouldn't it rather be
mysql_query("UPDATE table SET field = field WHERE user= '$user'");
I think you want to INSERT instead of using Update. Why field = field + ($userlogin)? This will concatenate the values. And one more thing please use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("INSERT INTO tanlename (field) VALUES (?)");
$stmt->bindParam(1, $user);
$stmt->execute();
?>
Use mysql_real_escape_string() after mysql connection and
Use double quotes
mysql_query("UPDATE table SET field = field + ({$userlogin})");
Use mysqli_query for you queries(notice the i) and use prepared statements. Using prepared statements is more secure than using straight queries and including the variable in the query string. Moreover, mysql will be deprecated soon. Example :
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>

How to create a secure mysql prepared statement in php?

I am new to using prepared statements in mysql with php. I need some help creating a prepared statement to retrieve columns.
I need to get information from different columns. Currently for a test file, I use the completely unsecure SQL statement:
$qry = "SELECT * FROM mytable where userid='{$_GET['userid']}' AND category='{$_GET['category']}'ORDER BY id DESC"
$result = mysql_query($qry) or die(mysql_error());
Can someone help me create a secure mysql statement using input from url parameters (as above) that is prepared?
BONUS: Prepared statements are suppose to increase speed as well. Will it increase overall speed if I only use a prepared statement three or four times on a page?
Here's an example using mysqli (object-syntax - fairly easy to translate to function syntax if you desire):
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
$stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1, $column2, $column3);
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}
$stmt->close();
Also, if you want an easy way to grab associative arrays (for use with SELECT *) instead of having to specify exactly what variables to bind to, here's a handy function:
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array(mysqli_stmt_bind_result, $fields);
}
To use it, just invoke it instead of calling bind_result:
$stmt->store_result();
$resultrow = array();
stmt_bind_assoc($stmt, $resultrow);
while($stmt->fetch())
{
print_r($resultrow);
}
You can write this instead:
$qry = "SELECT * FROM mytable where userid='";
$qry.= mysql_real_escape_string($_GET['userid'])."' AND category='";
$qry.= mysql_real_escape_string($_GET['category'])."' ORDER BY id DESC";
But to use prepared statements you better use a generic library, like PDO
<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT * FROM mytable where userid=? and category=?
order by id DESC');
$sth->execute(array($_GET['userid'],$_GET['category']));
//Consider a while and $sth->fetch() to fetch rows one by one
$allRows = $sth->fetchAll();
?>
Or, using mysqli
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$category = $_GET['category'];
$userid = $_GET['userid'];
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, 'SELECT col1, col2 FROM mytable where
userid=? and category=? order by id DESC')) {
/* bind parameters for markers */
/* Assumes userid is integer and category is string */
mysqli_stmt_bind_param($stmt, "is", $userid, $category);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $col1, $col2);
/* fetch value */
mysqli_stmt_fetch($stmt);
/* Alternative, use a while:
while (mysqli_stmt_fetch($stmt)) {
// use $col1 and $col2
}
*/
/* use $col1 and $col2 */
echo "COL1: $col1 COL2: $col2\n";
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
I agree with several other answers:
PHP's ext/mysql has no support for parameterized SQL statements.
Query parameters are considered more reliable in protecting against SQL injection issues.
mysql_real_escape_string() can also be effective if you use it correctly, but it's more verbose to code.
In some versions, international character sets have cases of characters that are not escaped properly, leaving subtle vulnerabilities. Using query parameters avoids these cases.
You should also note that you still have to be cautious about SQL injection even if you use query parameters, because parameters only take the place of literal values in SQL queries. If you build SQL queries dynamically and use PHP variables for the table name, column name, or any other part of SQL syntax, neither query parameters nor mysql_real_escape_string() help in this case. For example:
$query = "SELECT * FROM $the_table ORDER BY $some_column";
Regarding performance:
The performance benefit comes when you execute a prepared query multiple times with different parameter values. You avoid the overhead of parsing and preparing the query. But how often do you need to execute the same SQL query many times in the same PHP request?
Even when you can take advantage of this performance benefit, it is usually only a slight improvement compared to many other things you could do to address performance, like using opcode caching or data caching effectively.
There are even some cases where a prepared query harms performance. For example in the following case, the optimizer can't assume it can use an index for the search, because it must assume the parameter value might begin with a wildcard:
SELECT * FROM mytable WHERE textfield LIKE ?
Security with MySQL in PHP (or any other language for that matter) is a largely discussed issue. Here are a few places for you to pick up some great tips:
http://webmaster-forums.code-head.com/showthread.php?t=939
http://www.sitepoint.com/article/php-security-blunders/
http://dev.mysql.com/tech-resources/articles/guide-to-php-security.html
http://www.scribd.com/doc/17638718/Module-11-PHP-MySQL-Database-Security-16
The two most major items in my opinion are:
SQL Injection: Be sure to escape all of your query variables with PHP's mysql_real_escape_string() function (or something similar).
Input Validation: Never trust the user's input. See this for a tutorial on how to properly sanitize and validation your inputs.
If you're going to use mysqli - which seems the best solution to me - I highly recommend downloading a copy of the codesense_mysqli class.
It's a neat little class that wraps up and hides most of the cruft that accumulates when using raw mysqli such that using prepared statements only takes a line or two extra over the old mysql/php interface
Quite late, but this might help someone:
/**
* Execute query method. Executes a user defined query
*
* #param string $query the query statement
* #param array(Indexed) $col_vars the column variables to replace parameters. The count value should equal the number of supplied parameters
*
* Note: Use parameters in the query then supply the respective replacement variables in the second method parameter. e.g. 'SELECT COUNT(*) as count FROM foo WHERE bar = ?'
*
* #return array
*/
function read_sql($query, $col_vars=null) {
$conn = new mysqli('hostname', 'username', 'user_pass', 'dbname');
$types = $variables = array();
if (isset($col_vars)) {
for ($x=0; $x<count($col_vars); $x++) {
switch (gettype($col_vars[$x])) {
case 'integer':
array_push($types, 'i');
break;
case 'double':
array_push($types, 'd');
break;
default:
array_push($types, 's');
}
array_push($variables, $col_vars[$x]);
}
$types = implode('', $types);
$sql = $conn->prepare($query);
$sql -> bind_param($types, ...$variables);
$sql -> execute();
$results = $sql -> get_result();
$sql -> close();
}else {
$results = $conn->query($query) or die('Error: '.$conn->error);
}
if ($results -> num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$result[] = $row;
}
return $result;
}else {
return null;
}
}
You can then invoke the function like so:
read_sql('SELECT * FROM mytable where userid = ? AND category = ? ORDER BY id DESC', array($_GET['userid'], $_GET['category']));

Categories