I have a problem with mysql and php - php

I have a problem, this is my code:
$db = new mysqli("localhost", "root", "", "blah");
$result1 = $db->query("select * from c_register where email = '$eml' and password = '$pass'");
if($result1->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'client';
promptUser("You have successfully logged in!!!","index.php");
}
$db = new mysqli("localhost", "root", "", "blah");
$result2 = $db->query("select * from b_register where email = '$eml' and password = '$pass'");
if($result2->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'business';
promptUser("You have successfully logged in!!!","index.php");
}
$db = new mysqli("localhost", "root", "", "blah");
$result3 = $db->query("select * from g_register where email = '$eml' and password = '$pass'");
if($result3->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'employee';
promptUser("You have successfully logged in!!!","index.php");
}
$db = new mysqli("localhost", "root", "", "blah");
$result4 = $db->query("select * from k_register where email = '$eml' and password = '$pass'");
if($result4->fetch_array())
{
$auth->createSession();
$_SESSION['user'] = 'super';
promptUser("You have successfully logged in!!!","index.php");
}
else
{
promptUser("Username/Password do not match. Please try again!!!","");
}
Funny enough this code works, but I no that I went about it the wrong way. I am new with php and mysql, so please help. I also tried e.gresult4->free(); for all the variable that save the data, and I got this error: Fatal error: Call to a member function free() on a non-object in...

Don't repeat yourself. You already made your mysqli object, so reuse it. For example:
$db = new mysqli("localhost", "root", "", "blah");
$result1 = $db->query("select * from c_register...");
$result2 = $db->query("select * from d_register...");
$result3 = $db->query("select * from e_register...");
This will make your code more legible, and easier to modify later.

mysqli::query() returns a result object only after a successful query.
You need to build in a check:
if(($result1 != false) and ($result1->fetch_array())) // The same for 2,3,4...
you should get the error message using
echo $db->error;

From PHP Manual:
mysqli::query returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
So you should test it:
if ($result != false) {
...
} else {
// print error or whatever
}
Btw. it is VERY DANGEROUS not to escape variables like $eml and $pass - if a user type as $pass something like:
bleh' OR 1 = 1 OR password = 'bleh, then the whole query will look like:
select * from b_register where email = 'some#email.com' and password = 'bleh' OR 1 = 1 OR password = 'bleh'
and the user will get logged without knowing the password!
Therefore you should use: mysql_real_escape_string($eml) and the same for $pass.
Or even better: use statement preparing and parameters binding - see: http://pl2.php.net/manual/en/mysqli.prepare.php

Related

PHP Warning: query and fetch

Warning: mysqli_query() expects at least 2 parameters,1 given
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, null given
I have those warnings as well, how can I fix this?
public static function checklogin() {
mysqli_connect();
$username = $_SESSION['USER'];
$password = $_SESSION['PASS'];
$query = "
SELECT
`account`.`id`,
`account`.`status`
FROM `account`.`account`
WHERE `account`.`login` = '".$username."'
AND `account`.`password`='".$password."'
";
$exec = mysqli_query($query);
$row = mysqli_fetch_assoc($exec);
if($row['status'] == 'OK&apos
{
return true;
}
else
{
return false;
}
}
You need to save the database connection open with mysqli_connect, and in order to actually connect to the db the host configuration. Read the connect docs here for better explanation.
Update your code with a db address (make sure you know your connection)
$db=mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if(!$db) {
echo "ERROR connecting to my_db";
return false;
}
// sanitize
$username = filter_var($_SESSION['USER'], FILTER_SANITIZE_STRING);
$password = filter_var($_SESSION['PASS'], FILTER_SANITIZE_STRING);
$query = "
SELECT
`account`.`id`,
`account`.`status`
FROM `account`.`account`
WHERE `account`.`login` = '".$username."'
AND `account`.`password`='".$password."'
";
$exec = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($exec);
...
Have a look at the mysqli_querydocs.

Can't check if user exists in database PHP

I have a situation where I have to check if user exists in database, I try this:
$username = htmlspecialchars($_POST['userName']);
/* Check if username is free*/
if(!isset($error_message)) {
if(!isset($_POST["userName"])) {
$error_message = " All Fields are required";
} else {
$db_handle = new mysqli("localhost", "root", "pass", "database");
$query = 'SELECT * FROM naudotojai WHERE username = "$username"';
$result = $db_handle->query($query);
if($result->num_rows == 0) {
$error_message = "Do not exist";
}
}
}
But It doesn't work. It always returns 0 rows even if I enter a valid username that exists in database.
mysqli_result Object ( [current_field] => 0 [field_count] => 7 [lengths] => [num_rows] => 0 [type] => 0 )
Then I have second script, where I check if username is free, that works just fine:
$username = htmlspecialchars($_POST['userName']);
/* Check ir username is free*/
if(!isset($error_message)) {
if(!isset($_POST["userName"])) {
$error_message = " All Fields are required";
} else {
$db_handle = new mysqli("localhost", "root", "pass", "database");
$query = 'SELECT * FROM naudotojai where username = "$username"';
$result = $db_handle->query($query);
if(!empty($result)) {
$error_message = "Exists";
}
}
}
Could you help me out with this? Can't figure it out on my own.
EDIT: When I enter the username manually it just works fine. So the problem is with the variable in the query. But I don't get It. Why It works on one query but not the other....
$query = 'SELECT * FROM naudotojai WHERE username = admin';
You are using a single quote string to build your query, so you string $username is not replaced.
Try to use
"SELECT * FROM naudotojai where username = '$username'"
But a better approach would be to use a prepared statement to avoid SQL injection.
You can use PDO with PHP.
}else{
$dbh = new PDO('mysql:host=localhost;dbname=database', "root", "pass");
$sth = $dbh->prepare("SELECT * FROM naudotojai where username = :username");
$sth->execute(":username" => $username);
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
if($result){
// do something
}
}

PDO Insert not working with bindParam

I am currently using PDO to connect to my database and it works, but when a user logs in, I want it to check if the user's id is already in a row, I have already done this in the code below:
<?php
require 'steamauth/steamauth.php';
if(!isset($_SESSION['steamid'])) {
$username = "Unknown";
$avatar = "defaultUser";
$accid = "Unknown";
$credits = "Not Applicable";
$avatarSmall = "smallUser"; //For Dashboard
} else {
include ('steamauth/userInfo.php');
$username = &$steamprofile['personaname'];
$avatar = &$steamprofile['avatarmedium'];
$accid = &$steamprofile['steamid'];
$avatarSmall = &$steamprofile['avatar']; //For Dashboard
$db_user = "USERNAME";
$db_pass = "PASSWORD";
$db_host = "HOST";
$db_name = "DATABASE NAME";
$db = new PDO("mysql:host=".$db_host.";db_name=".db_name, $db_user, $db_pass);
try{
$check = $db->prepare("SELECT userID from userData WHERE userID = :accountID");
$check->bindParam(':accountID', $accid, PDO::PARAM_INT);
$check->execute();
if(!$check){
die("Server Error: 404Check, Please Contact A Member Of Staff If This Error Continues.");
}else{
if($check->rowCount() > 0) {
$creditsQuery = $db->prepare("SELECT userCredits FROM userData WHERE userID = :accountID3");
$creditsQuery->bindParam(":accountID3", $accid, PDO::PARAM_INT);
$creditsQuery->execute();
//Set Credits To Variable From Database Column
$credits = $creditsQuery->fetch(PDO::FETCH_ASSOC);
}else{
$sql = $db->prepare("INSERT INTO userData (userID, userCredits) VALUES (:accountID2, '0')");
$sql->bindParam(':accountID2', $accid, PDO::PARAM_INT);
$sql->execute();
if(!$sql){
die('Server Error: 404Insert, Please Contact A Member Of Staff If This Error Continues.');
}
}
}
}catch(PDOException $e){
die ("Server Error: 404Connection, Please Contact A Member Of Staff If This Error Continues.");
}
}
?>
Although, when I login, it doesn't seem to store the user's id or credits as 0, and the table (userData) is empty.
Thanks,
Matt
This is wrong:
$check->execute();
if(!$check){
^^^^^^^
$check doesn't magically change into a boolean true/false if the execute fails. It will ALWAYS be a prepared statement object, and therefore always evaluate to true.
You didn't enable exceptions in PDO, therefore it runs in the default "return false on failure" mode, which means your code should be:
$res = $check->execute();
if(!$res) {
die(...);
}
And this holds true for your other prepare/execute blocks as well - Your script is killing itself before it ever gets to the insert query, because your test for database failure is wrong.

Query MySQL with PHP

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

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