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

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']);

Related

multiple query in one php file , i tried to write the code but i am not getting it done

I want to execute mysql_qry1 also , how should i do it , till now my code is working fine but i want to execute the second query also(mysql_qry1) , please help.
<?php
require "conn.php";
$status=1;
$user_name = $_POST["user"];
$user_pass = $_POST["pass"];
$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
$mysql_qry1 = "insert into login_status (username, status) values ('$user_name','$status)";
$result = mysqli_query($conn , $mysql_qry);
if(mysqli_num_rows($result)==1) {
echo "login success , Hello";
}
else {
echo "login failed";
}
$conn->close();
?>
Your SQL is one of most dangerous, please try to re-write:
//$mysql_qry = "select * from tbl_client where username like '$user_name' and password like '$user_pass'";
I m not sure what is in our conn.php, here is one of the example to update (PDO):
$sql = 'select 1 from tbl_client where username = :user and password = :pass';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':pass' => $user_pass);
$row = $sth->fetch(PDO::FETCH_NUM);
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
$sql = 'insert into login_status (username, status) values (:user, :status)';
$sth = $dbL->prepare($sql);
$sth->execute(':user' => $user_name, ':status' => $status);
OK, so your conn.php is using mysqli_ . Please refer to this page for help:
http://php.net/manual/en/mysqli-stmt.bind-param.php
And change above answer to:
$sql = 'select 1 from tbl_client where username = ? and password = ?';
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $user_name, $user_pass);
mysqli_stmt_execute($stmt);
$row = mysqli_stmt_fetch();
if ($row[0]) {
echo 'Login OK';
} else {
echo 'Login Failed';
}
I have not used mysqli before, so not quite familiar, even php.net is hard to find out some docs about it. Please google howto use: mysqli_stmt_fetch() and replace it with proper code
Why not update your conn.php to use PDO? (be careful, you might need to update all your other pages as well which are calling this file):
// conn.php
$pdo = 'mysql:host=' . $server_name . ';dbname=' . $db_name;
$dbL = new PDO($pdo, $mysql_username, $mysql_password);

PHP Register Script - check user exists not working

I've got a problem with my PHP Registration Script that firstly checks, if the user exists.
It always outputs "false".
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$database = #mysql_connect("***********", "********", "******") or die("Can't connect to the server. Error: ".mysql_error());
//$username = mysql_real_escape_string($username);
$passwort = hash("sha256", $passwort);
$numrows = mysql_query("SELECT * FROM *******.mikgames WHERE username='".$username."' LIMIT 1");
$checkuserexists = mysql_num_rows($numrows);
if($checkuserexists==0) {
$abfrage = mysql_query("INSERT INTO *******.mikgames (username,passwort) VALUES ('$username', '$passwort')");
echo'true';
}
else {
echo'false';
}
?>
Edit: Now I'am using MySQLi and I've changed the code into this:
<?php
$username = $_GET['username'];
$passwort = $_GET['passwort'];
$con = mysqli_connect('************','******','******') or die(mysqli_error());
mysqli_select_db($con, "*******") or die("cannot select DB");
$passwort = hash("sha256", $passwort);
$query = mysqli_query($con,"SELECT * FROM *******.mikgames WHERE username='".$username."'");
$result = mysqli_num_rows($query);
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames (username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
echo 'true';
}
else {
echo 'false';
}
?>
And it works.
You could go one step better and take an OOP approach using the PDO driver; PDO invokes security by allowing secure parameter binding and uses the SQL preferred functions.
Inside your pdo_driver.php file:
namespace ProjectName\App\Drivers;
if(!defined('IN_PROJECTNAME'))
{
die('No Script Kiddies Please...');
}
interface EntityContainer
{
public function query($statement, array $values = array());
}
class Entity extends \PDO implements EntityContainer
{
public function __construct(
$dsn = 'mysql:host=XXXX;dbname=XXXX', $user = 'XXXX', $pass = 'XXXX'
) {
try {
parent::__construct($dsn,$user,$pass);
} catch (PDOException $ex) {
die('FATAL ERROR: ' . $ex->getMessage());
}
}
public function query(
$statement, array $values = array()
) {
$smpt = parent::Prepare($statement);
(empty($values)) ? $smpt->execute() : $smpt->execute($values);
return $smpt;
}
}
Inside any other php file:
define('IN_PROJECTNAME', 0);
require_once dirname(__FILE__) . '/path/to/pdo_driver.php';
$container = array();
$container['Connection'] = new ProjectName\App\Drivers\Entity();
$username = $_GET['username'];
$passwort = $_GET['passwort'];
if(empty($container['Connection']->query('SELECT passwort FROM ******.mikgames WHERE username = ?', [$username])->fetch()['passwort'])) {
$container['Connection']->query('INSERT INTO ******.mikgames (username,passwort) VALUES (?, ?)', [$username,$passwort]);
}
Two Factors:
Firt Factor
You need to add an error output for debugging purposes:
$query = mysqli_query($con,"SELECT * FROM <tablename> WHERE
username='".$username."'") or die(mysqli_error($con));
I can't see a clear error with the information you have displayed here so far so you should also check what the value of $username acutally is and how closely it fits the value in the DB. Also read and take on board what the error output tells you.
Second Factor:
Your problem is you're running/articulating a query twice, here:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_query($con,$abfrage);
You see $abfrage is a MySQL result object and you're then plugging it back into a MySQL query call, with the variable declaration $result. So your result is querying a query. This is an error.
What you probably want to do is use MySQLi_affected_rows to count how many rows have been inserted and run the appropriate IF clause:
if($result==0) {
$abfrage = mysqli_query($con, "INSERT INTO ********.mikgames
(username,passwort) VALUES ('$username', '$passwort')");
$result = mysqli_affected_rows($con);
echo 'true';
}
else {
echo 'false';
}
Use #mysql_***** for your ptoject.
$sql="SELECT * FROM table_name";
$result=#mysql_query($sql, $conn);
while ($name = # mysql_fetch_array($result)){
echo $name ['username'];
}
You just used simple mysql_***

Inserting data to mysql not working

<?
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?

Switch from mysql_connect to PDO: mysql_num_rows() expects parameter 1 to be resource

I had code that used mysql_connect which I understand is now deprecated to I switched to the following code (I'm working locally):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$DBusername = 'admin';
/*** mysql password ***/
$DBpassword = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
But this now means that a function of mine breaks:
$result = mysql_num_rows($query);
Because, following the script back, the connection is not working. There is something up with my PDO connection script but I do not understand what I have done wrong. The details are correct for logging into phpMyAdmin on localhost.
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
PDO is entirely independent from the mysql extension, you will have to update your function calls as well. mysql_query for example should be a combination of prepare and execute.
As a note: Please please use Prepared Statements, your example query is completely insecure.
As an example was requested:
// initialize PDO
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
// Prepare a query
$sql = "SELECT COUNT(*) AS count
FROM users
WHERE username = ?
LIMIT 1";
$statement = $dbh->prepare($sql);
// execute the query
$statement->execute(array($username));
// retrieve the first row
$row = $statement->fetch();
if ($row['count']) echo 'The user exists';
else echo 'The user does not exist';

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.

Categories