Unable to store data via mysqli_connect - php

Hey guys currently I'm trying to create a login activity for android application and I have no idea why the user data is not stored upon registration. Is there something wrong with the php files as shown below?
Register.php stores registration for users
<?php
$con = mysqli_connect("mysql13.000webhost.com", "a1641537_fetch", "password", "a1641537_fetchdb");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO Fetch (name, username, password) VALUES (?, ?, ?) ");
mysqli_stmt_bind_param($statement, "sss", $name, $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
FetchUserData.php fetches username and password of a user.
<?php
$con = mysqli_connect("mysql13.000webhost.com", "a1641537_fetch", "password", "a1641537_fetchdb");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM Fetch WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $name, $username, $password);
$user = array();
while(mysqli_stmt_fetch($statement)) {
$user[name] = $name;
$user[username] = $username;
$user[password] = $password;
}
echo json_encode($user);
mysqli_stmt_close($statement);
mysqli_close($con);
?>

fetch is a reserved word in mysql so you need to quote it in backticks.
For example:
$statement = mysqli_prepare($con, "INSERT INTO `Fetch` (name, username, password) VALUES (?, ?, ?) ");
To catch these kinds of mistakes, it is useful to add error handling. I prefer to do that by having msyqli throw an exception when anything goes wrong.
To activate that, just add mysqli_report(MYSQLI_REPORT_STRICT); to the top of your script and make sure that errors are displayed.
If you don't add any try - catch blocks yourself, php will show you a detailed unhandled exception error when a problem occurs so you can take it from there. Obviously in live code this is not the preferred way to handle that.

Related

"Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, boolean given in" [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I'm getting these warnings from web host which contains my database. I'm trying to get an Android app developed in Android Studio to send data from a Register user activity to a database. I think I'm having a PHP Script error.
Below is my PHP code for registering user:
<?php
$con = mysqli_connect("localhost", "user", "pass", "db");
if (isset($_POST["name"], $_POST["email"], $_POST["username"], $_POST["password"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
}
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, email, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $username, $email, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
You have check for errors:-
<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);
$con = mysqli_connect("localhost", "id2833909_split421", "pass123", "id2833909_splitw");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (isset($_POST["name"], $_POST["email"], $_POST["username"], $_POST["password"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO `user` (`name`, `username`, `email`, `password`) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssss", $name, $username, $email, $password); // i need to be s
$response = array();
if(mysqli_stmt_execute($statement)){
$response["message"] = "success";
}else{
$response["message"] = "error";
}
echo json_encode($response);
}
?>

PHP not posting onto mySQL database

This code should check for existing usernames and if there isn't one, it should create a new one. No matter what it won't add. Additionally, as you can see in the code it only echoes 'here' and doesn't echo 'not here'.
<?php
$password = "hey";
$username = "hi";
require "conn.php";
//$password = $_POST["password"];
//$username = $_POST["username"];
echo 'here';
$result = $conn->query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
echo 'not here';
if ($result) {
if($result->num_rows === 0)
{
$stmt = $conn->prepare("INSERT INTO UserData (username,password) VALUES (:username,:password)");
$params = array(
':username' => $username,
':password' => $password
);
$stmt->execute($params);
}
}
?>
This is the connection code:
<?php
//$db_name = "xxx";
//$mysql_username = "xxx";
//$mysql_password = "xxx";
//$server_name = "xxx";
// Create connection
$conn = new mysqli("xxx","xxx","xxx","xxx");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Changes:
<?php
require "conn.php";
echo "debug 1";
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', /*$_POST["username"]*/ $username );
$username = 'hi';
$stmt->execute();
$stmt->store_result();
echo "debug 2";
if ($stmt->num_rows == 0){ // username not taken
echo "debug 3";
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password =(/*$_POST["password"]*/ "hey");
$username =(/* $_POST["username"]*/ "hi");
$stmt2->bind_param('s',$username);
$stmt2->bind_param('s',$password);
$stmt2->execute();
if ($stmt2->affected_rows == 1){
echo 'Insert was successful.';
}else{ echo 'Insert failed.';
var_dump($stmt2);
}
}else{ echo 'That username exists already.';}
?>
This code gets through all of the debugs but for some reason, it is still not inserting.
Replace this line
$result = **$mysqli->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
with following
$result = **$conn->**query("SELECT * FROM UserData WHERE username ='$username' ", MYSQLI_USE_RESULT);
The mysqli and PDO interfaces must not be mixed. Here the database connection and the SELECT query are both using the mysqli interface. But the second INSERT query is attempting to use the PDO interface, as evidenced by the use of named placeholders, and also the passing of a data array directly to execute(). The latter two features are not supported by mysqli, hence the code fails at the second query. Also, note that the second query is using prepared statements, while the first one is not. Again, different approaches should not be mixed together.
Also it appears that passwords are being stored as plain text, with no security. The proper approach is to use the password_hash function.
Just ensure that the database field has enough width (say 80-120 characters or more) to handle the current bcrypt hash, plus allow some more for future changes.
Staying with the mysqli interface (and with password_hash), the code could go something like this:
$stmt = $conn->prepare("SELECT * FROM UserData WHERE username = ?");
$stmt->bind_param('s', $_POST["username"]);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0){ // username not taken
$stmt2 = $conn->prepare("INSERT INTO UserData (username, password) VALUES (?, ?)");
$password = password_hash($_POST["password"], PASSWORD_DEFAULT);
$stmt2->bind_param('s', $_POST["username"]);
$stmt2->bind_param('s', $password);
$stmt2->execute();
if ($stmt2->affected_rows == 1)
echo 'Insert was successful.';
else echo 'Insert failed.';
}
else echo 'That username exists already.';
Note that the above approach would not be suitable for a high-traffic site, where there is a chance condition of another user trying to INSERT the same username, during the brief interval of time between the SELECT and INSERT database queries. That would require a different approach, like ensuring the subject database field is set to UNIQUE (which is good practice anyway), and then testing for violation of that UNIQUE field upon attempted duplicate insertion.
Assuming database and INSERT permissions are all set up OK and it is still not inserting, try enhancing the error-reporting.
Ensure the following are at the top of the page:
ini_set('display_errors', true);
error_reporting(E_ALL);
And put the following before the first query:
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
Then try again.

PHP pdo insert query not working

<?php
// DATABASE-HOSTNAME-OR-IPADDRESS-GOES-HERE
// MYSQL-DBNAME-GOES-HERE
class LoginHandler {
public $dbHostname = 'localhost';
public $dbDatabaseName = 'employee101';
public $user = 'root';
public $password = 'root';
public function handleRequest($arg) {
$username = '123';
$password2 = '123';
$fname = 'John';
$lname = 'Doe';
$age = '18';
if ( ! $username ) {
$this->fail();
return;
}
try {
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$sql="SELECT * FROM `employee_data` WHERE `username`='$username'";
$stmt = $pdo->query($sql);
if ( $stmt === false ) {
echo "DB Critical Error";
return;
}
elseif ( $stmt->rowCount() > 0 ) {
echo "user already exists";
return;
}
else {
echo "User created";
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES ($fname, $lname, $age, $username, $password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam($fname, $_POST[$fname], PDO::PARAM_STR);
$stmtz->bindParam($lname, $_POST[$lname], PDO::PARAM_STR);
$stmtz->bindParam($age, $_POST[$age], PDO::PARAM_STR);
$stmtz->bindParam($username, $_POST[$username], PDO::PARAM_STR);
$stmtz->bindParam($password2, $_POST[$password2], PDO::PARAM_STR);
$resultzzx = $stmtz->execute();
return;
}
}
catch(PDOException $e) {
$this->log('Connection failed: ' . $e->getMessage());
echo "DB Critical Error";
}
}
function log($msg) {
file_put_contents("login.log", strftime('%Y-%m-%d %T ') . "$msg\n", FILE_APPEND);
}
}
$handler = new LoginHandler();
$handler->handleRequest($_POST);
?>
When attempting to use this script above, I get the echo that the user was created, but even when refreshing the table, the new entry doesn't show up.
Now, if i change the values line to be the following, it will work and show the new entry.
('John', 'Doe', '18', $username, $password2)";
What am i doing wrong? I need the first name, last name and age entries to not be concrete, as i will be obtaining them from a POST on my android device. The whole purpose of this script is to create the user and it's records if it doesn't already exist.
You have various mistakes.
1) You are not binding your parameters correctly. To bind them correctly, you place a :variablename in the position you want to include the variable. Usually the "variablename" should be the same as the one you are obtaining from the $_POST superglobal so that the code is cleaner and more readable.
2) You are not obtaining the values from the $_POST superglobal correctly. The key values you place inside are strings, and by placing an empty $fname variable, you are not going to obtain a correct result. It would only work if you had coding saying $fname = 'fname' somewhere up top hidden from us, however that code itself would be unadvised since it is unnecessary and only makes the source code larger.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password)
VALUES (:fname, :lname, :age, :username, :password2)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host=
{$this>dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':fname', $_POST['fname']);
$stmtz->bindParam(':lname', $_POST['lname']);
$stmtz->bindParam(':age', $_POST['age']);
$stmtz->bindParam(':username', $_POST['username']);
$stmtz->bindParam(':password2', $_POST['password2']);
I hope that helps.
$sql = "INSERT INTO employee_data (name, sumame, age, username, password) VALUES (:name, :sumame, :age, :username, :password)";
$dsn = "mysql:dbname={$this->dbDatabaseName};host={$this->dbHostname};port=8888";
$pdo = new PDO($dsn, $this->user, $this->password);
$stmtz = $pdo->prepare($sql);
$stmtz->bindParam(':name', $fname);
$stmtz->bindParam(':sumame', $lname);
$stmtz->bindParam(':age', $age);
$stmtz->bindParam(':username', $username);
$stmtz->bindParam(':password', $password2);
$resultzzx = $stmtz->execute();
return;
After reviewing the link Fred posted in the comment above, i've modified it to work fine, thanks.

Cannot fetch the name,username and password

When I try to login it shows Incorrect user details. Although the data is getting inserted but not getting fetched.
Following are my two PHP files.
Register.php
<?php
$con=mysqli_connect("mysql.hostinger.in","name","password","u721174658_swap");
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO `user` (name,username, password) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "sss", $name,$username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
mysqli_close($con);
?>
FetchUserData.php
<?php
$con=mysqli_connect("mysql.hostinger.in","name","password","u721174658_swap");
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT * FROM `user` WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $userID, $name,$username, $password);
$user = array();
while(mysqli_stmt_fetch($statement)){
$user["name"] = $name;
$user["username"] = $username;
$user["password"] = $password;
}
echo json_encode($user);
mysqli_close($con);
?>
use to fetch the following way and session start
while($row= mysql_fetch_array($statement){
$name = $row['name'];
}

Retrieving uuid from mysql query

I assign uuid() to the id field. It works perfectly. But I don't know how to echo the generated uuid back to the user. How can I do this?
My code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (id,firstname, lastname, email)
VALUES (UUID(),:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john#example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
You can't.
Your only choice is separating this into two queries.
SELECT UUID()
Retrieve created UUID into a php variable ($uuid)
Insert that variable into your prepared statement.
$stmt = $conn->prepare("INSERT INTO MyGuests (id,firstname, lastname, email)
VALUES (:uuid,:firstname, :lastname, :email)");
$stmt->bindParam(':uuid', $uuid);
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

Categories