Inserting data to mysql not working - php

<?
session_start();
if(($connection = mysql_connect("localhost", "root", "")) == false)
die ("Couldn't connect to database");
if(mysql_select_db("Social", $connection) == false)
die ("Couldn't select db");
if (isset($_POST['username']) && isset($_POST['pass']) && isset($_POST['login'])){
$sql = sprintf("SELECT * FROM users WHERE username LIKE '%s' AND password LIKE '%s'", $_POST['username'], $_POST['pass']);
$query = mysql_query($sql);
if (mysql_num_rows($query) == 0){
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['newUser'], $_POST['newPass']);
$query2 = mysql_query($sql2);
if (!$query2){
print "Registration failed";
}
else{
print "Registration sucessfull";
}
}
?>
My program is not inserting any data into mySQL table. I know all the syntax is right, everything should work out fine. I double checked on the command that mySQL uses in order to enter data into the table. Why is this not working? My query2 should be successful, but idk why its not.
Please help.
Thanks

to prevent sql injections, try mysqli or pdo
here is mysqli prepared statements version. However if you are trying to create user management system, I wouldn't recommend you do it. There are so many scripts which provide more security, http://www.usercake.com is a good user management system.
session_start();
$db = new mysqli('localhost', 'root', 'password', 'database');
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_POST['username'] && $_POST['pass'] && $_POST['login']))
{
$user_name = ''; //define these here.
$pass = '';
$stmt = $db->prepare("select * from users where username = ? and password = ?");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $user_name, $pass);
$stmt->execute();
$result = $stmt->get_result();//get rows
if($result->num_rows < 1) //check if result is less than 1
{
$error = "<br />Wrong Username or Password";}
else{
$_SESSION['user'] = $_POST['username'];
header("Location: home1.php");
}
}
if (isset($_POST['register'])){
$uname = $_POST['newUser'];
$pass = $_POST['newPass'];
if(empty($uname))
{
echo "Please enter your username.";
}
elseif(empty($pass))
{
echo "Please enter your password.";
}
else{
$stmt = $db->prepare("insert into Social.users (username, password) values (?,?)");
echo $db->error;//this will echo the error.
$stmt->bind_param('ss', $uname, $pass);
$stmt->execute();
echo "You have successfully registered.";
}
}

The variables in the INSERT must be the username and password
$sql2 = sprintf("INSERT INTO Social.users (username, password) VALUES (%s, %s)", $_POST['username'], $_POST['pass']);
Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
Using PDO:
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
Using mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name =
?'); $stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result(); while ($row = $result->fetch_assoc()) {
// do something with $row }
Font: How can I prevent SQL injection in PHP?

Related

Having trouble creating a safe way for users to update their data

I am making a way for users to edit their data. My first way I did it worked, but then I remembered that it is very insecure and that I should never insert data directly into the database; at least that's what I was told. I try to make it more secure by doing the VALUES (?,?,?,?,?) thing so that the data is not directly going in, which seemed to work fine in my registration page (which I can include if you want).
To start, here is my original update data page that worked fine but it does not use the (?,?,?,?,?) method:
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
Here is what I tried to do to make it more secure but this doesn't seem to work. Specifically the $query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'"; seems to be the issue, though the syntax looks fine to me
if(isset($_POST['submit'])) {
$userid=$_SESSION['userid'];
$skype=$_POST['skype'];
$email=$_POST['email'];
$region=$_POST['region'];
$crank=$_POST['league1'];
$drank=$_POST['league2'];
if(empty($skype) || empty($email) || empty($crank) || empty($drank) || empty($region))
{
echo "Cannot leave any field blank";
}
else
{
$host= "localhost";
$dbname = "boost";
$user = "root";
$pwd = "";
$port=3306;
try
{
$mysqli= new mysqli($host, $user, $pwd, $dbname,$port);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssss",$skype,$email,$region,$crank,$drank);
$stmt->execute();
$iLastInsertId=$mysqli->insert_id;
header('Location: http://localhost/Boost/account.php');
$stmt->close();
$mysqli->close();
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
}
So I am not sure what the problem is. In my experience with PHP, the syntax should be fine but I must be missing something.
It's quite simple actually, you went from
$query = "UPDATE usertable SET SkypeID = '$skype', Email = '$email', Region = '$region', CRank = '$crank', DRank = '$drank' WHERE UserID = '$userid'";
TO
$query = "UPDATE usertable SET usertable(SkypeID,Email,Region,CRank,DRank) VALUES (?,?,?,?,?) WHERE UserID = '$userid'";
It appears you confused an INSERT statement vs. an UPDATE statement when rewriting so to fix you simply use your old statement with the new style...
$query = "UPDATE usertable SET SkypeID = ?, Email = ?, Region = ?, CRank = ?, DRank = ? WHERE UserID = $userid";

PHP/MySQL: Check if username exists

I'm a beginner in php and I want to check if the username entered already exists.
Here is my code.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
include "connect.php";
ValidateUser();
}
function ValidateUser()
{
if (!empty($_POST['username']) AND !empty($_POST['password'])) {
$queryrow=mysqli_query("SELECT * FROM websiteusers WHERE username = '$_POST['username']'");
if ($rows=mysqli_num_rows($queryrow)=0) {
RegisterUser();
}
}
function RegisterUser() {
echo "works up to here";
}
?>
It doesn't even give me an error despite turning error reporting on.
Have you even initialized a mysqli_connect?
$Connection = mysqli_connect("host","user","pass","database");
Then pass it to a function which uses mysqli_query() by:
function foo ($DB){
mysqli_query($DB,"QUERY HERE");
// Do other stuff
return /* Whatever you wish to return here*/
}
foo($Connection);
What you are trying to achieve can be done very easily with the following code. A bigger concern is security. It is good practice to both sanitize your input every time the user has a chance to input text.
Also, using prepared query's will put yet another layer of security.
Although this isn't using your provided code directly, I believe it is good to teach good habits.
If you have any questions feel free to ask.
$username = $_POST['username']; <-- sanitize this
$message = null;
$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
if ($stmt->num_rows() > 0) {
RegisterUser();
} else {
$message .= 'username already exists';
}
Later on when you require more items to be queried, or more results to be bound:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username); <-- the "s" means the argument is a strings, if a argument is stored as an int use "i", but one character for each argument is required.
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
$stmt->fetch();
Multiple Arguments:
$stmt = $mysqli->prepare("SELECT username,password,other1,other2 FROM websiteusers WHERE username=? AND authenticated=?");
$stmt->bind_param('si', $username,$isauthenticated); <-- second argument is a INT or BOOL
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql,$passwordsql,$other1sql,$other2sql);
$stmt->fetch();
When your expecting multiple results, and lets say you want to dump them into arrays:
$userarray = array();
$stmt = $mysqli->prepare("SELECT username FROM websiteusers WHERE username=?");
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($usernamesql);
while($stmt->fetch()){
array_push($userarray, $usernamesql);
}
$userarray is now an array of all the results fetched from the database.
Here is the right way to do this:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if(check_user($mysqli, $_POST['username']){
registerUser();
}else{
echo 'user exist, cannot register';
}
}
function check_user($conn, $username){
$query = "SELECT * FROM websiteusers WHERE username = ?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->close();
}
return $stmt->num_rows === 0;
}
function registerUser() {
echo "registering user ...";
}
Read up on prepared statement

Mysqli prepared statements error? [duplicate]

This question already has answers here:
mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
(2 answers)
Closed 1 year ago.
I've ran into this error with prepared statements, I've just started with prepared statements so go easy on me please, Heres the error:
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in C:\wamp\www\darkhorizons\login.php on line 31
Heres my code:
if (isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(isset($username) && isset($password)) {
$mysqli = new mysqli("localhost","root","","phplogin") or die("Couldnt connect!");
if(mysqli_connect_errno()){
echo "Connection failed: ". mysqli_connect_errno();
exit();
}
if($stmt = $mysqli -> prepare("SELECT * FROM users WHERE username =? AND password =? LIMIT 1")){
$stmt -> bind_param("ss", $username, $password);
$stmt -> execute();
$stmt -> bind_result($result);
$stmt -> fetch();
$numrows = mysqli_num_rows($result);
} else {
die("Please enter a username and password!");
}
if($numrows == 1){
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true ;
$query = "SELECT adminflag FROM users WHERE username = '{$_SESSION['username']}' LIMIT 1;";
$result2 = mysqli_query($connect, $query);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 == 1) {
$_SESSION['isadmin'] = true;
}
header("Location: {$pageLoc}");
exit(); //It's good to use exit or die (same thing) AFTER using header to redirect
} else {
}
}
}
As a side note, Please ignore any mistakes in the code below the prepared statement, im redoing my login script that ive been using to learn.
Going through your code you didn't really need to query you DB twice, you should read the adminflag in that same select.
SELECT * is never a good idea always select specific fields.
And I also noticed you are using two differnt style, I suggest you to stick to the Object oriented approach.
<?php
if (isset($_POST['submit'], $_POST['username'] , $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$mysqli = new mysqli("localhost","root","","phplogin");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT adminflag FROM users WHERE username = ? AND password = ? LIMIT 1";
if ($stmt = $mysqli->prepare($query)) {
$stmt -> bind_param("ss", $username, $password);
$stmt->execute();
$stmt->store_result();
$numrows = $stmt->num_rows;
printf("Number of rows: %d.\n", $numrows );
if($numrows == 1){
$stmt->bind_result($admin_flag);
$stmt->fetch();
session_start();
if ($admin_flag== 1) {
$_SESSION['isadmin'] = true;
}
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true ;
header("Location: {$pageLoc}");
}else{
echo 'user not found';
}
}
$stmt->close();
$mysqli->close();
}else{
echo 'required field missing';
}
?>

PHP registered user check

I have PHP + AS3 user login&register modul.I want to check registered user by username.But can't do it because I'm new at PHP.If you can help it will helpfull thx.(result_message part is my AS3 info text box.)
<?php
include_once("connect.php");
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES ('$username', '$password', '$userbio')";
mysql_query($sql) or exit("result_message=Error");
exit("result_message=success.");
?>
Use MySQLi as your PHP function. Start there, it's safer.
Connect your DB -
$host = "////";
$user = "////";
$pass = "////";
$dbName = "////";
$db = new mysqli($host, $user, $pass, $dbName);
if($db->connect_errno){
echo "Failed to connect to MySQL: " .
$db->connect_errno . "<br>";
}
If you are getting the information from the form -
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
you can query the DB and check the username and password -
$query = "SELECT * FROM users WHERE username = '$username'";
$result = $db->query($query);
If you get something back -
if($result) {
//CHECK PASSWORD TO VERIFY
} else {
echo "No user found.";
}
then verify the password. You could also attempt to verify the username and password at the same time in your MySQL query like so -
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password';
#Brad is right, though. You should take a little more precaution when writing this as it is easily susceptible to hacks. This is a pretty good starter guide - http://codular.com/php-mysqli
Using PDO is a good start, your connect.php should include something like the following:
try {
$db = new PDO('mysql:host=host','dbname=name','mysql_username','mysql_password');
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Your insert would go something like:
$username = $_POST['username'];
$password = $_POST['password'];
$userbio = $_POST['userbio'];
$sql = "INSERT INTO users (username, password, user_bio) VALUES (?, ?, ?)";
$std = $db->prepare($sql);
$std = execute(array($username, $password, $userbio));
To find a user you could query similarly setting your $username manually of from $_POST:
$query = "SELECT * FROM users WHERE username = ?";
$std = $db->prepare($query)
$std = execute($username);
$result = $std->fetchAll();
if($result) {
foreach ($result as $user) { print_r($user); }
} else { echo "No Users found."; }
It is important to bind your values, yet another guide for reference, since I do not have enough rep yet to link for each PDO command directly from the manual, this guide and website has helped me out a lot with PHP and PDO.

PHP mysql_real_escape_string(); whats the correct method using mysqli?

its a little difficult to explain. I've build the mysql function which works fine and with the depreciation of mysql I will need to change this function to use mysqli rather than the mysql method.
I current have:
$con = mysql_connect("host", "username", "pass");
mysql_select_db("db", $con);
$Username = mysql_real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$Query = mysql_query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'") or die(mysql_error());
$Query_Res = mysql_fetch_array($Query, MYSQL_NUM);
if($Query_Res[0] === '1')
{
//add session
header('Location: newpage.php');
}
else {
echo 'failed login';
}
Now I've applied mysqli to this and it's not returning any data or errors but the function still complies.
$log = new mysqli("host", "user", "pass");
$log->select_db("db");
$Username = $log->real_escape_string($_POST['user']);
$Password = hash_hmac('sha512', $_POST['pass'], '&R4nD0m^');
$qu = $log->query("SELECT COUNT(*) FROM users WHERE username = '{$Username}' AND password = '{$Password}'");
$res = $qu->fetch_array();
if($res[0] === '1'){
//add session
header('Location: newpage.php');
}
else {
$Error = 'Failed login';
sleep(0.5);
}
echo $res['username'].' hello';
}
But I'm unsure on why this is wrong. I know it's probably a simply answer
Just to have it as an answer:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.prepare.php
e.g.
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
You may check if the connection is establishing before using real_escape_string()
if ($log->connect_errno) {
echo "Failed to connect to MySQL: (".$log->connect_errno.")".$log->connect_error;
}
afaik, there's no problem with $log->real_escape_string($_POST['user']);

Categories