This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
<?php
$conn = mysql_connect("localhost", "root", "") or die ('Error connecting to MySQL!');
mysql_select_db("aspire");
$earnedpoints = false;
$account = $_POST['name'];
$account = mysql_real_escape_string($account);
if ($account == "") {
echo 'Enter an account name!';
exit();
}
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$query = mysql_query("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='$account' OR ip='$ip'");
$lasttime = mysql_fetch_array($query);
$amount = $lasttime['amount'];
$insertnew = false;
if ($amount == "") {
$insertnew = true;
}
$timecalc = $time - $lasttime['date'];
if (!$insertnew) {
if ($timecalc < 21600) {
echo ' Hello '. $account .' you have already voted with this account ('. $account .') or IP ('. $ip .') in the last 6 hours!';
echo ' Last voted on: '. date('M d\, h:i:s A', $lasttime['date']) .'';
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="10; url=/">';
echo '</head>';
echo '<body>';
echo '<br><br>You will be redirected to the main website in 10 seconds.';
echo '</body>';
echo '</html>';
exit();
} else {
$update = mysql_query("UPDATE votingrecords SET account='$account', date='$time', times=times+1 WHERE ip='$ip'");
if (!$update) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $update;
die($message);
} else {
$earnedpoints = true;
}
}
} else {
$success = mysql_query("INSERT INTO votingrecords (`account`, `ip`, `date`, `times`) VALUES ('$account', '$ip', '$time', 1)");
if (!$success) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $success;
die($message);
} else {
$earnedpoints = true;
}
}
if ($earnedpoints) {
$points = mysql_query("UPDATE accounts SET votepoints = votepoints + 2 WHERE name='$account'");
if (!$points) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($conn);
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.gtop100.com/in.php?site=80994">';
echo '</head>';
echo '</html>';
} else {
echo 'There was an error processing your request.';
exit();
}
?>
Hey everyone,
I'm very inexperienced with PHP scripting and I've been told that my script is vulnerable to SQL injection? But I'm not sure how I would make it to be SQL injection proof since I'm not much experienced in that field and i'm afraid I might mess up the code.
Could anyone help me with this? I would greatly appreciate it.
How can I prevent SQL injection in PHP?
Your code is really escaping the input values but mysql_connect is deprecated in PHP 5.5 and totally dropped in PHP 7.
Using parametric query is your best option:
You need to firstly open connection, instead of
$conn = mysql_connect("localhost", "root", "") or die ('Error connecting to MySQL!');
mysql_select_db("aspire");
You will open connection like this
$mysqli = new mysqli("localhost", "root", "", "aspire");
Then prepare your query, instead of putting query like this
$query = mysql_query("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='$account' OR ip='$ip'");
You will put it like this
$stmt = $mysqli->prepare("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='?' OR ip='?'");
This one is a prepared statement, it is not you that will put your query input, it is PHP that will do it for you, all you need to do is to bind your query input with that $stmt like this
$stmt->bind_param("s", $account);
$stmt->bind_param("s", $ip);
You are having two inputs which are $account and $ip, the account and ip are both string which happens to be what the s stands for... you will now execute the statement, like this
$stmt->execute();
And don't forget to close connection that you opened
$stmt->close();
see this link
http://php.net/manual/en/pdo.prepared-statements.php
use prepared statements and stored procedures
Related
Recently I've bought webhosting at names.co.uk and I'm trying to set up something simple which will display the name from a table named Team if the id = 1.
This is my code
<?php
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysql_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysql_fetch_array($result);
echo '<br />tryed fetching row';
if ($row === FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysql_error());
}
echo $name;
?>
This is the output:
Query is send Result is true tryed fetching rowNo such file or
directory
UPDATE:
I have changed to msqli:
$q = "SELECT * FROM `Team` WHERE id =1";
$result = mysqli_query($q);
echo '<br />Query is send';
echo '<br />Result is true';
$row = mysqli_fetch_array($result);
echo '<br />tryed fetching row';
if ($row !== FALSE) {
echo '<br />$row is not false.';
$name = $row['name'];
echo '<br />$name now is "' . $name . '"';
}
else {
echo( mysqli_error());
}
echo $name;
and now I'm getting this output:
Query is send Result is true tryed fetching row $row is not false.
$name now is ""
You need to fist establish a connection. For example: $connection = mysqli_connect($servername, $username, $password);.
See this link on how to use MySQLi: https://www.w3schools.com/PHP/php_mysql_connect.asp (but note that w3schools is a bad resource, with outdated information and bad practices - I'm only linking to it because this tutorial is basic and clear).
Be sure to check later, if you still haven't, on how to properly sanitize your queries. See this, for example: How can I prevent SQL injection in PHP?
Use function:
$result = mysqli_query($q);
mysql_query() have been deprecated in PHP7 onwards.
this is my first question here so please do not roast on me.
I am currently working on a html, php, mysql project in school and I want to know if it is possible to compare the entry of a form in html with a table in my database to get its id.
The form looks like
Prename:""
Last name:" "
The table:
ID: '1'
Prename:'abc'
Last name: 'xyz'
Now, if someone fills out the form and submit, I want to send it to a function which looks through the database and if a match is found, returns the ID.
Thanks for your ideas!
Edit: As you want here is what I got so far includes the code from #Patchesoft
Still it isnt working
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="db_class.php" method="post">
<p>Vorname: <input type="text" name="prename"/></p>
<p>Nachname: <input type="text" name="last_name"/></p>
<input type="submit" name="submit" value="Start"/>
</form>
</body>
</html>
And for the PHP part our teacher got us a class with a lot of functions to add and select from databases etc. The most important:
<?php
DB::init(...); // The connection is ok. I just delted the login data for purpose
$prename = mysqli_real_escape_string($_POST['prename']);
$lastname = mysqli_real_escape_string($_POST['last_name']);
$result = mysqli_query("SELECT `ID` FROM `user` WHERE `prename` = '" . $prename . "' AND `last_name` = '" . $lastname . "' ");
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
return $row['ID'];
}
echo $result;
class DB {
public static $db = null;
public static $insertID;
public static function init($dbHost, $dbUser, $dbPassword, $dbName) {
self::$db = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
if (self::$db->connect_errno) {
$_SESSION['errors'][] = "MySQL connection failed: ". self::$db->connect_error;
}
self::$db->query("SET NAMES utf8;");
}
public static function select($table, $columns = '*', $key=null, $where = null, $limit = null, $debug = false) {
$sql = "SELECT " . self::generateColumnList($columns) . " FROM $table";
if ($where != null) {
$sql .= " WHERE ".$where;
}
if ($limit != null) {
$sql .= " LIMIT ".$limit;
}
if ($debug == true) {
$_SESSION['debug'][] = __FUNCTION__ . ': $sql is <strong>' . $sql . '</strong>';
}
$result = self::$db->query($sql);
if (self::$db->errno) {
$_SESSION['errors'][] = '<p>select failed: ' . self::$db->error . '<br> statement was: <strong>' . $sql . '</strong></p>';
return array();
} else {
$ret = array();
while ($row = $result->fetch_assoc()) {
if (!empty($key)){
$ret[$row['id']] = $row;
}
else
$ret[] = $row;
}
if (count($ret) == 1) {
return $ret[0];
} else {
return $ret;
}
}
}
public static function select2($sql, $debug = false) {
$result = self::$db->query($sql);
if (self::$db->errno) {
$_SESSION['errors'][] = '<p>select failed: ' . self::$db->error . '<br> statement was: <strong>' . $sql . '</strong></p>';
return array();
} else {
$ret = array();
while ($row = $result->fetch_assoc()) {
if (!empty($key)){
$ret[$row['id']] = $row;
}
else
$ret[] = $row;
}
if (count($ret) == 1) {
return $ret[0];
} else {
return $ret;
}
}
}
You will want to get your form input fields into variables and then make an SQL query that checks the data in your database. It's quite simple, but for a beginner there are some other things to consider.
1) Sanitizing your input. This is important to protect against SQL Injection attacks. The simple answer is to run it through mysql_real_escape_string() function to clean the variable, but there are much more better methods than this. Look up prepared statements.
2) Connecting to your database. Before you can do any querying to your database, you need to connect to it. It's quite simple to do, but you will need to look up how to do this.
As for some base code, try:
$prename = mysqli_real_escape_string($_POST['prename']);
$lastname = mysqli_real_escape_string($_POST['lastname']);
// Now check to see if the values match in your database
// This assumes you have already written your connecting to database code
$result = mysqli_query("SELECT `ID` FROM `table_name` WHERE `prename` = '" . $prename . "' AND `lastname` = '" . $lastname . "' ");
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
return $row['ID'];
}
This is a very basic script- it's what I as a beginning learned doing. There are much better ways of doing it, using PDO database drivers. But if you're just learning to do something in PHP and MySQL, this should get you going.
I've searched and tried a couple of different ways but I always get a 0000-00-00 00:00:00
Here's my page:
<?php
require_once "../../maincore.php";
require_once THEMES."templates/header.php";
$earnedpoints = false;
$account = $_GET['account'];
$account = mysql_real_escape_string($account);
if ($account == "") {
echo 'Enter an account name!';
exit();
}
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$query = mysql_query("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='$account' OR ip='$ip'");
$lasttime = mysql_fetch_array($query);
$amount = $lasttime['amount'];
$insertnew = false;
if ($amount == "") {
$insertnew = true;
}
$timecalc = $time - $lasttime['date'];
if (!$insertnew) {
if ($timecalc < 43200) {
require_once THEMES."templates/header.php";
add_to_title(" - Vote");
opentable("Error");
echo "<table class='tbl-border' width='100%' cellspacing='1' cellpadding='5'><td class='tbl2'>";
echo ' Hello '. $account .' you have already voted with this account ('. $account .') or IP ('. $ip .') in the last 12 hours!';
echo ' Last voted on: '. date('Y-m-d H:i:s', $lasttime['date']) .'';
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="10; url=\vote.php?account=' . $_GET['account'] . '">';
echo '</head>';
echo '<body>';
echo '<br /><br /><center>You will be redirected to the main website in 10 seconds.</center>';
echo '</body>';
echo '</html>';
echo "</td></table>";
closetable();
require_once THEMES."templates/footer.php";
exit();
} else {
$update = mysql_query("UPDATE votingrecords SET account='$account', date='NOW()', times=times+1 WHERE ip='$ip'");
if (!$update) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $update;
die($message);
} else {
$earnedpoints = true;
}
}
} else {
$success = mysql_query("INSERT INTO votingrecords (`account`, `ip`, `date`, `times`) VALUES ('$account', '$ip', 'NOW()', 1)");
if (!$success) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $success;
die($message);
} else {
$earnedpoints = true;
}
}
if ($earnedpoints) {
$points = mysql_query("UPDATE user SET votingpoints = votingpoints + 1 WHERE login='$account'");
if (!$points) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close();
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=vote here">';
echo '</head>';
echo '</html>';
} else {
echo 'There was an error processing your request.';
exit();
}
require_once THEMES."templates/footer.php";
?>
That solved my problem with it not inserting the date, that works fine now!! thanks alot!
I thought it would solve my issue with it not keeping track of when a user votes so they can only vote each 12 hours.It still lets people vote over and over again >.<
Is there anyway to bump this? Lmao.. Still could use some help
Don't put NOW() inside of single quotes...
I just checked the code and you have 'NOW()' in the insert take out quotes and use just now().
'NOW()' will be treated as string and while adding to mysql datetime field its invalid and thus will have 0000-00.....
i'm getting back to make some php code to make a login/register form.
Account data is stored in mysql database and I've used that code to validate the md5 and parse it trough the browser. But there's something wrong 'cause it doesn't work.
<?php
if (!$x) {
echo "<script type='text/javascript'>document.location.href='index.php';</script>";
} else {
$con = mysql_connect('localhost', 'userdb', 'pwd') or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
$result = mysql_query("SELECT * FROM `users` WHERE `md5pwd` = '". $x ."'");
$num = $result1->num_rows;
if($num == 0){
//if not display an error message
echo "<script> alert('Usuario inexistente') </script>";
echo "<script type='text/javascript'>document.location.href='index.php';</script>";
}else{
while($row=mysql_fetch_object($result1)){
$userName=$row->username;
echo "<script> alert('BIENVENIDO " . $userName . "') </script>";
echo "[ " . $userName . " ]\n\n";
}
}
}
?>
I hope you can understand and I hope you can help me. I'm unhappy.
thanks
Hope it helps you, $num = mysql_num_rows($result); instead of $num = $result1->num_rows;
mysql_fetch_object($result) instead of mysql_fetch_object($result1)
<?php
if (!$x) {
echo "<script type='text/javascript'>document.location.href='index.php';</script>";
} else {
$con = mysql_connect('localhost', 'userdb', 'pwd') or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
$result = mysql_query("SELECT * FROM `users` WHERE `md5pwd` = '". $x ."'");
$num = mysql_num_rows($result);
if($num == 0){
//if not display an error message
echo "<script> alert('Usuario inexistente');document.location.href='index.php';</script>";
}else{
while($row=mysql_fetch_object($result)){
$userName=$row->username;
echo "<script> alert('BIENVENIDO " . $userName . "') </script>";
echo "[ " . $userName . " ]\n\n";
}
}
}
?>
Note: mysql_* functions deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
Working code:
<?php
if (!isset($x)) {
echo "<script type='text/javascript'>document.location.href='index.php';</script>";
} else {
$con = mysql_connect('localhost', 'userdb', 'pwd') or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
$result = mysql_query("SELECT * FROM `users` WHERE `md5pwd` = '". $x ."'");
$num = mysql_num_rows($result);
if($num == 0){
//if not display an error message
echo "<script> alert('Usuario inexistente') </script>";
echo "<script type='text/javascript'>document.location.href='index.php';</script>";
}else{
while($row=mysql_fetch_object($result)){
$userName=$row->username;
echo "<script> alert('BIENVENIDO " . $userName . "') </script>";
echo "[ " . $userName . " ]\n\n";
}
}
}
?>
PS: mysql_extension will be removed in the future, use mysqli or PDO...btw mysqli in procedural mode it's very similar to mysql extension.
Hello i have the following code that validates that a form has data in it and then i want to make sure that the Name, Email and Address arent already in my database before i insert it...
Can you tell where i am messing up with the below it is throwing the already exists error even when it is unique data
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter a name!</li>";
}
if(empty($_POST['formEmail']))
{
$errorMessage .= "<li>You forgot to enter an email!</li>";
}
if(empty($_POST['formAddress']))
{
$errorMessage .= "<li>You forgot to enter your Address!</li>";
}
if(empty($_POST['formCity']))
{
$errorMessage .= "<li>You forgot to enter your City!</li>";
}
if(empty($_POST['formState']))
{
$errorMessage .= "<li>You forgot to enter your State!</li>";
}
if(empty($_POST['formZip']))
{
$errorMessage .= "<li>You forgot to enter your Zip!</li>";
}
$varName = $_POST['formName'];
$varEmail = $_POST['formEmail'];
$varAddress = $_POST['formAddress'];
$varCity = $_POST['formCity'];
$varState = $_POST['formState'];
$varZip = $_POST['formZip'];
$varDate = $_POST['formDate'];
if(empty($errorMessage))
{
$db = mysql_connect("localhost","root","PASSWORD");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("FormData" ,$db);
$dupesql = "SELECT * FROM formdata WHERE (name = '$varName' AND email = '$varEmail' AND address = '$varAddress')";
$duperaw = mysql_query($dupesql);
if($duperaw > 0) {
echo ("$varName already exists in $varAddress \n");
}
else {
$sql = "INSERT INTO formdata (name, email, address, city, state, zip, submitDate) VALUES (".
PrepSQL($varName) . ", " .
PrepSQL($varEmail) . ", " .
PrepSQL($varAddress) . ", " .
PrepSQL($varCity) . ", " .
PrepSQL($varState) . ", " .
PrepSQL($varZip) . ", " .
PrepSQL($varDate) . ")";
mysql_query($sql);
header("location: index.php?success=1");
exit();
}
}
}
Use mysql_num_rows($duperaw) > 0 instead of just $duperaw > 0 to check if your query returned any results.
Also, avoid using mysql_* functions. They are no longer maintained and are deprecated as of PHP 5.5.0. Read this post for a more detailed explanation. Instead, use PDO or MySQLi and learn about prepared statements. This article can help you decide which MySQL API to use.