PHP file not retrieving data from my mySQL database server - php

I am currently coding an Android app for login and registration. I have discovered that the error is coming from my php file as when I try and just open the file it does not fetch any of the data even though it is connecting correctly to the database.
This is my PHP code here:
<?php
$con=mysqli_connect("mysql7.000webhost.com","a3736257_root","********","a3736257_UD");
if ($con->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo 'connection successful';
$username = 'jack';
$password = 'jackjack';
$statement = mysqli_prepare($con, "SELECT * FROM Parent WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute;
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement,$parentID ,$username, $password, $email, $created, $rewardOwed);
$parent = array();
while(mysqli_stmt_fetch($statement)) {
$parent[username] = $username;
$parent[password] = $password;
$parent[email] = $email;
$parent[created] = $created;
}
echo json_encode($parent);
mysqli_stmt_close($statement);
mysqli_close($con); ?>
This is the output when I execute the code

The mysqli_stmt_execute function doesn't know what you want it to execute unless you provide it with the prepared statement. Also functions should have parenthesis ().
So:
mysqli_stmt_execute;
should be
mysqli_stmt_execute($statement);

Related

PHP inserting with bind_param

I am currently working trying to use the statements mysqli_prepare and bind_param in order to pass arguements more safely into my query. I was doing mysqli_query to execute them before which worked fine. My professor is requiring us to use prepare though. I currently am getting the proper values from my form but the data isn't being entered into customer table. Also, I have mysqli_error() on my execute() commands but I am not getting any errors at all which is making debugging difficult. Here is the php part located in register.php
<?php
require 'connection.php';
$result = "";
if(isset($_POST['register'])) {
#Fetch the data from the fields
$username = $_POST['username'];
$password = $_POST['password'];
$name = $_POST['name'];
$total = 0.0;
#echo $username . " " . $password . " " . $name . " " . $total;
#Prepare sql query to see if account already exists
$query = mysqli_prepare("SELECT * FROM customer WHERE username=?");
$query->bind_param("s", $username);
$query->execute() or die(mysqli_error());
if(mysqli_num_rows($query) > 0) {
#This username already exists in db
$result = "Username already exists";
} else {
$insert = mysqli_prepare("INSERT INTO customer(username, password, name, total) VALUES (?, ?, ?, ?)");
$insert->bind_param("sssd", $username, $password, $name, $total);
$insert->execute() or die(mysqli_error());
#$result = "Account registered!"
}
}
?>
I establish connection to my db like this in connection.php
$conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
Like I said before, I can get the query to execute with mysqli_query but for some reason I cannot get param to work. Also tried adding or die but no errors are being printed

Problems with my first prepared MySQLi

Following a question earlier about sanitising a string, I'm now attempting to use the principles seen at How can I prevent SQL injection in PHP?
$connection = mysqli_connect('localhost', 'user', 'xxxxx');
$database = mysqli_select_db($connection, 'xxxxx');
$param1 = $_GET['q'];
//prepared mysqli statement
$stmt = mysqli_stmt_init($connection);
$stmt = $connection->prepare('SELECT * FROM CONTACTS WHERE SURNAME = ?');
$stmt->bind_param('s', $param1); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
$num_rows = mysqli_num_rows($result);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
while ($row = $result->fetch_assoc()) {
echo $result['COMPANY']." ".$result['FORENAME']." ".$result['SURNAME'];
}
However, although $connection and $database are both processing correctly, I'm getting the following error:
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/my_first_mysqli.php on line xxxx
Am I not getting the syntax correct or does it have more to do with the php version 5.2.0 I'm rocking. (Yes, I'm upgrading code before upgrading server).
If it's the latter, is there a simpler MySQLi method I can use that will work before I upgrade the php version?
EDIT
I've updated this now which is a bit cleaner:
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $param1);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);
/* fetch value */
mysqli_stmt_fetch($stmt);
$num_rows = mysqli_num_rows($stmt);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
/* close statement */
mysqli_stmt_close($stmt);
mysqli_close ($conn);
I'm obviously not getting a recordset result to loop through and don't know how to... The rest appears to work without throwing an error.
Thanks for all the contributions. I now have a working procedural solution that I thought I'd post for reference.
It's a bit cumbersome but it's fine and I believe it follows good modern practice.
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
$conn = new mysqli($servername, $username, $password, $dbname);// Create connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
mysqli_stmt_bind_param($stmt, "s", $param1);// bind parameters for markers
mysqli_stmt_execute($stmt);// execute query
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);// bind result variables
// fetch values
while (mysqli_stmt_fetch($stmt)) {
echo $CONTACTID."<br>";
echo $COMPANY."<br>";
echo $FORENAME."<br>";
echo $SURNAME."<br>";
echo "<hr/>";
}
mysqli_stmt_close($stmt);// close statement
mysqli_close ($conn);
Feedback welcome if you can see any improvements.

password_verify having a few issues hopefully someone can help me

So im making a login for a game system that uses a JSON string to read back the files, however when I Hash the password and try login it doesn't work however when the password is unhased it works fine, I think the problem lies with the password verify part.
Im just unsure where to place it if someone could guide me in the right direction that will be amazing...
So the issue is when I send the $password example test5 it only reads as test 5 and not this $2y$10$viov5WbMukXsCAfIJUTUZetGrhKE9rXW.mAH5F7m1iYGfxyQzQwD.
This was the original Code
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
$mysqli->close();
}
Then I tried This
<?php
include("dbconnect.php");
/////// First Function To Get User Data For Login
if($_GET["stuff"]=="login"){
$mysqli = new mysqli($DB_host, $DB_user, $DB_pass, $DB_name);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/////// Need to Grab Username And Password
$username = $_GET["user"];
$password = $_GET["password"];
$GetPassword = "SELECT password FROM users WHERE username='$username'";
$data = mysqli_query($GetPassword);
if(password_verify($password, $data['password'])) {
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($username, $password, $regkey, $banned);
while ($stmt->fetch()) {
echo "{";
echo '"result": "success",';
echo '"regkey": "' . $regkey . '",';
echo '"banned": "' . $banned . '"';
echo "}";
}
$stmt->close();
}
} else {
// password is in-correct
}
$mysqli->close();
}
$data = mysqli_query($GetPassword);
^^^---mysqli result handle/object
if(password_verify($password, $data['password'])) {
^^^^^^^^^^^^---no such element in mysqli
You never fetched your data results, so you're comparing the entered password against a non-existent element of the $data result object/handle.
You need
$row = mysqli_fetch_assoc($data);
password_verify(..., $row['password']);
Most likely you're running with error_reporting and display_errors disabled, meaning you'd never see the "undefined index" warnings that PHP would ave been throwing everytime you ran this code. Those settings should NEVER be off on a devel/debug system.
And note that you're vulnerable to sql injection attacks, so your "security" system is anything but -it's entirely useless and trivially bypassable.
There are several issues with your code, such as:
This statement $data = mysqli_query($GetPassword) is wrong. mysqli_query() expects first argument to be your connection handler, so it should be,
$data = mysqli_query($mysqli, $GetPassword);
Look at this statement, if(password_verify($password, $data['password'])) { ...
mysqli_query(), on success, returns a result set, so you can't get the password using $data['password']. First fetch the row from the result set and then get the password, like this,
$row = mysqli_fetch_assoc($data);
if(password_verify($password, $row['password'])) { ...
Look at the following query,
$query = "SELECT username, password, regkey, banned FROM users WHERE username='$username' and password='$password'";
This query won't return any rows because of this WHERE condition, ...password='$password'. So the solution is, instead using two separate queries, use only one query to validate the password and retrieve relevant data. The solution is given down below.
Your queries are susceptible to SQL injection. Always prepare, bind and execute your queries to prevent any kind of SQL injection.
If you want to build a json string then instead of doing echo "{"; echo '"result": "success",'; ..., create an array comprising of all the relevant data and then json_encode the array.
So the solution would be like this:
// your code
$username = $_GET["user"];
$password = $_GET["password"];
// create a prepared statement
$stmt = mysqli_prepare($mysqli, "SELECT username, password, regkey, banned FROM users WHERE username=?");
// bind parameters
mysqli_stmt_bind_param($stmt, 's', $username);
// execute query
mysqli_stmt_execute($stmt);
// store result
mysqli_stmt_store_result($stmt);
// check whether the SELECT query returned any row or not
if(mysqli_stmt_num_rows($stmt)){
// bind result variables
mysqli_stmt_bind_result($stmt, $username, $hashed_password, $regkey, $banned);
// fetch value
mysqli_stmt_fetch($stmt);
if(password_verify($password, $hashed_password)){
echo json_encode(array('result' => 'success', 'regkey' => $regkey, 'banned' => $banned));
}else{
// incorrect password
}
}else{
// no results found
}
mysqli_stmt_close($stmt);
// your code

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

SQL - How to return multiple rows that have identical field in php

I'm using this php script to access a remote database from an android app. I am trying to search for Games with a certain location to find all the games going on at that location. The problem is my php file is only returning me the most recently created game, is there a way I can go through and return all the games one by one if there are 2 games with the same value for 'location'?
<?php
/*server, user, password, databse */
$conn=mysqli_connect("x", "x", "x","x");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$location = $_POST["location"];
$statement = mysqli_prepare($conn, "SELECT * FROM Games WHERE location = ?");
if($statement === FALSE){ die(mysqli_error($conn)); }
mysqli_stmt_bind_param($statement, "s", $location);
mysqli_stmt_execute($statement);
//printf("Error: %s.\n", mysqli_stmt_error($statement));
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $user, $time, $date, $num_players, $location);
$game = array ();
while(mysqli_stmt_fetch($statement)){
$game[user] = $user;
$game[time] = $time;
$game[date] = $date;
$game[num_players] = $num_players;
$game[location] = $location;
}
echo json_encode($game);
mysqli_stmt_close($statement);
mysqli_close($conn);
?>

Categories