Passing PHP variable to SQL query - php

$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();
?>

Related

SELECT * FROM and mysqli_fetch_array using Prepared Statements

After a long time avoiding Prepared Statements I want to leave my comfort zone and update all my sites to mysqli, but I'm having a really hard time to achieve things that seem simple before...
Connection
$conn = mysqli_connect($host, $user, $password, $database)or die(mysqli_error($conn));
All my query's were built this way:
$id = 1;
$result = mysqli_query($conn, "SELECT * FROM users WHERE id = '$id'");
$row = mysqli_fetch_array($result);
Then I could print all needed fields:
Name: $row['name'];
Email: $row['email'];
Address: $row['address'];
City: $row['city'];
...
I've tried several ways to prepare, execute, bind and fetch the results in a simple way, or similar to what I was used to, but none of them work for me.
My statement is that bad? I mean, if I sanitize all itens before any Query or Insert my statement will remain insecure?
Can anyone show me a example of how can I use prepared statement but still be able to print my results individually, like: $row['name], $row['address'], $row['city']...
JUST TO UPDATE A FEW THINGS
This code works properly, my connection is ok and the $id is declared above my query (I've edited my question). My question is how can I "transform" this code into a mySQLi Prepared Statement and still be able to print results individually like $row['name'], $row['address']...
<?php
$mysqli = new mysqli("localhost", "username", "password", "db_name");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id =1;
if ($stmt = $mysqli->prepare("SELECT name, email from users where id=?")) {
/* bind parameters for markers */
$stmt->bind_param("d", $id);
/* execute query */
$stmt->execute();
$stmt->bind_result($name, $email);
/* fetch value */
$stmt->fetch();
printf("%s has email %s", $name, $email);
/* close statement */
$stmt->close();
}
?>
May it help

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>";
}

Check if value exists in MySQL table

I am very new to MySQl and I'm trying to check if an inputed email matches with any from my table. If it matches, I need to put the email and the other columns of the same row in another table.
What I get now is a blank row added to table2.
<?php
include "config.php";
$email = $_POST['email'];
$match = mysqli_query("SELECT email FROM table1 WHERE email = $email");
if($conn->query($match)){
//here i have to find the name, school, and grad_year that matches
// with the email from table 1 which is in the same row. I tried a couple of
//things but it didn't work. So i don't know what to put in there.
$insert = "INSERT INTO table2 VALUES(name,'$email',school,grad year )";
$conn->query($insert);
}
?>
Any help would be much appreciated!
Don't ever use the mysql* functions. They are deprecated and insecure. Use mysqli* or PDO instead. See below for sample code (I have NOT run it and there may be errors - the idea is to get you on the right road...)
<?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();
}
$email = $_POST['email'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM table1 WHERE email=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $email);
/* execute query */
$stmt->execute();
/* bind result variables */
# NOTE: You may prefer $stmt->get_results() and $result->fetch_assoc()
# to this $stmt->bind_result() and $stmt->fetch().
$stmt->bind_result($name, $junk, $school, $grad_year);
/* fetch value */
if ($stmt->fetch()) {
$stmt2 = $mysqli->prepare("INSERT INTO table2 VALUES (?,?,?,?)");
$stmt2->bind_param("ssss", $name, $email, $school, $grad_year);
$stmt2->execute();
$stmt2->close();
}
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Or, if you don't care to know details along the way, this is a lot faster and simpler:
// yada,yada - get a conx
$email = $_POST['email'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO table2 SELECT * FROM table1 WHERE email=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $email);
/* execute query */
$stmt->execute();
/* the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function */
}
(SOURCE: Example copied from http://php.net/manual/en/mysqli.prepare.php and modified)

Can't get mysql_query to return any values that exist in the database

I'm using the following snippet:
mysql_connect($host,$user,$password);
$sql = "SELECT FROM ec_opps WHERE id=" . $_GET["UPDATE"];
$item = mysql_query($sql);
mysql_close();
print_r($item);
To try and retrieve data based on the UPDATE value. This value prints to the page accurately, and I know the IDs I'm requesting exist in the database. The print_r($item) function returns no result, not even an empty array, so I'm confused as to where I'm going wrong.
I know it isn't best practise to use MySQL like this, but I'm doing it for a reason.
You're missing columns to be selected in your SELECT query, or you can select all by putting *, which means selecting all column.
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"]."'";
Your query is very prone to SQL injections.
You should refrain from using MySQL. It's deprecated already. You should be at least using MySQLi_* instead.
<?php
/* ESTABLISH CONNECTION */
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT column1, column2 FROM ec_opps WHERE id=?"; /* REPLACE NEEDED COLUMN OR ADD/REMOVE COLUMNS TO BE SELECTED */
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param("s", $_GET["UPDATE"]); /* BIND GET VALUE TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($column1,$column2); /* BIND RESULTS */
while ($stmt->fetch()) { /* FETCH RESULTS */
printf ("%s (%s)\n", $column1, $column2);
}
$stmt->close();
}
$mysqli->close();
?>
Replace with this code
$sql = "SELECT * FROM ec_opps WHERE id=" . $_GET["UPDATE"];
You are missing * in your query.
You need to use:
SELECT * FROM
instead of
SELECT FROM
There is a syntax error in the query. It is missing *. Try with -
$sql = "SELECT * FROM ec_opps WHERE id='" . $_GET["UPDATE"] . "'";
Please avoid using mysql. Try to use mysqli or PDO. mysql is deprecated now.

How to prevent mysql injection 1=1 using msqli? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
In my website users can submit posts and delete their posts.
To delete a post, they follow the link /posts.php?deletid=X where X is the id of the post in database (for example: 1).
When clicked, it will run the following:
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".mysql_real_escape_string($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}
The problem is that it's vulnerable to the 1=1 SQL injection. If they type into the address bar /posts.php?deletid=1 OR 1=1;
it will delete all posts on database.
In this question: How can I prevent SQL injection in PHP?, I realized I need to use mysqli statements, and I tried to make it work but with no success..
Can someone please tell me exactly how I can prevent this with mysqli?
You need to have the value in quotes for mysql_real_escape_string to have any useful effect.
$sql = "DELETE from `posts` WHERE `id`='".mysql_real_escape_string($deleteid)."'";
Alternatively, instead of mysql_real_escape_string, which is intended for strings, try intval.
With MySQLi and prepared statements you do not need to worry about this, as a parameter cannot be replaced by 1 OR 1=1 (or if it is provided as the parameter value, then it’s interpreted as a string).
By using prepared statements, the mysql_* functions are on there way out and soon tobe deprecated, one should not be writing new code with these functions, refactor your code.
PDO
<?php
$db = new PDO("mysql:host=localhost;dbname=yourDB", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
/*** prepare the SQL statement ***/
$query = $db->prepare("DELETE from `posts` WHERE `id`=:id;");
/*** bind the paramaters ***/
$query->bindParam(':id', $deleteid, PDO::PARAM_INT);
/*** execute ***/
$query->execute();
header('Location: posts.php');
exit();
?>
mysqli
<?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();
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("DELETE from `posts` WHERE `id`=?")) {
/* bind parameters for markers */
$stmt->bind_param("i", $deleteid);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
header('Location: posts.php');
exit();
?>
One thing first: if you can, it would be wise not to use mysql_* but e.g. mysqli_* functions or PDO, since the first are outdated. There you can use placeholders (?) instead of string concats. You don't have to care for quoting yourself there.
The easiest option in your example code would be to run all numbers through integer parsing (use intval).
if(isset($_GET['deleteid'])) {
$deleteid = $_GET['deleteid'];
$sql = "DELETE from `posts` WHERE `id`=".intval($deleteid).";";
$query = mysql_query($sql);
header('Location: posts.php');
exit();
}

Categories