PHP Registration script using prepared statements - php

I have got the following registration code, it SEEMS to be working but it isn't actually inserting the entered information into my table. It all runs with no errors showing up, and the "echo 'end';" is displaying.
Edit, updated code:
Now get this error
Warning: mysqli_stmt::bind_param(): Number of elements in type
definition string doesn't match number of bind variables in
C:\xampp\htdocs\ppa\test.php on line 19
Which is this line:
$insert_stmt->bind_param($email, $password, $random_salt, $user);
PHP:
<?php
include "includes/db_connect.php";
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
//Default user perms
$perms = "user";
$password = hash('sha512', $_POST['p']); //Need to add JavaScript to hash password before it gets here
//Create random salt
$random_salt = hash('sha512', uniqid(mt_rand(1, getrandmax()), true));
//Create salted password
$password = hash('sha512', $password.$random_salt);
//Add insert to database script
//Use prepared statements!
if ($insert_stmt = $mysqli->prepare("INSERT INTO users (email, password, salt, perms) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param($email, $password, $random_salt, $perms);
$insert_stmt->execute();
}
echo "Email: ".$email."<br />";
echo "Password: ".$password."<br />";
echo "Random Salt: ".$random_salt."<br />";
echo "Permissions: ".$perms."<br />";
}
?>
This is my db_connect.php page
<?php
define("HOST", 'localhost');
define("USER", 'ppa_user');
define("PASSWORD", 'password');
define("DATABASE", 'ppa');
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
//No database found, redirect to setup
$url = "http://".$_SERVER['HTTP_HOST'].'/ppa/setup.php';
header('Location: '.$url);
}
?>

In order to close this question as being answered, have come to the conclusion the OP needed to use the following code:
$insert_stmt->bind_param("ssss", $email, $password, $random_salt, $perms);

Replace the following:
//Add insert to database script
//Use prepared statements!
if ($insert_stmt = $mysqli->prepare("INSERT INTO users (email, password, salt, perms) VALUES (?, ?, ?, ?)"));
$insert_stmt->bind_param('ssss', $_POST['email'], $password, $random_salt, $user);
//Execute the prepared query
$insert_stmt->execute();
echo "end";
with:
//Add insert to database script
//Use prepared statements!
if ($insert_stmt = $mysqli->prepare("INSERT INTO users (email, password, salt, perms) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param($_POST['email'], $password, $random_salt, $user);
$insert_stmt->execute();
echo "end";
}

check this
if ($insert_stmt = $mysqli->prepare("INSERT INTO users (email, password, salt, perms) VALUES (?, ?, ?, ?)"));
$insert_stmt->execute(array($_POST['email'], $password, $random_salt, $user));

Related

What is the query binding marker for CURRENT_DATE when using mysqli prepared statements?

So I've finished building a question and answer site and am now trying to defend it against SQL injection but having problems with CURRENT_DATE. I want to insert current date with the question into db but what binding marker would that be? "s" for string is not working?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "questions87";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
$question = $_POST["question"];
$uname = $_SESSION['username'];
$qa_email =$_SESSION['email'];
// prepare and bind
$stmt = $conn->prepare("INSERT INTO login (username, username, q_date, qa_email) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $question, $uname, CURRENT_DATE, $qa_email);
$stmt->execute();
if ($stmt) {echo "Thank you ". $uname . " Your question has been submitted " . "<br>";}
else {echo "Error: " . $sql . "<br>" . mysqli_error($conn);}
$stmt->close();
$conn->close();
?>
Use simple mysql function NOW() and remove placeholder for q_date:
$stmt = $conn->prepare("INSERT INTO login (username, username, q_date, qa_email) VALUES (?, ?, NOW(), ?)");
$stmt->bind_param("sss", $question, $uname, $qa_email);
Btw, I noticed, you have field username twice in this query. I suppose one of the occurences should be replaced with some other field.

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

Unable to store data via mysqli_connect

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.

PHP Mysqli no errors, no querys

I'm trying to use mysqli instead of mysql queries, and it's not working.
Mysqli:
$mysqli->connect($db1['host'], $db1['user'], $db1['password'], $db1['database']);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
no errors. If I try this query:
if(isset($_POST['username']))
{
$password = $_POST['p'];
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
$password = hash('sha512', $password.$random_salt);
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
$insert_stmt->execute();
}
echo "Success";
}
nothing is inserted, no errors with mysqli error.
Table structure is correct, and it says success. I'm new to mysqli, I'm used to mysql. Is there something I've missed with error reporting?
you have to do it like this way
$password = hash('sha512', $password.$random_salt);
$insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)");
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
if($insert_stmt->execute())
{
echo "Success";
}
Actually you are first checking the query and after that binding the params, because of that it was just displaying Success.
Better try this, its from php manual
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli- >connect_error;
}
You could do the $stmt->execute(); in an if loop like this:
if ($stmt->execute()){
$result = $stmt->affected_rows;
if ($result) { echo "yay" } else { echo "boo"; }
}
else {
printf("Execute error: %s", $stmt->error);
}

what is wrong with this code

class MyClass {
private $db;
// Constructor
function __construct() {
$this->db = new mysqli('localhost', 'root', 'root', 'Test_db');
$this->db->autocommit(FALSE);
}
// Destructor
function __destruct() {
$this->db->close();
}
// Main method
function MyFun() {
// Check for required parameters
if (isset($_POST["name"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["email"])) {
echo "Before \n";
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$activation = 0;
echo "After \n";
// tracking
$stmt = $this->db->prepare("INSERT INTO users (name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("is", $name, $username, $password, $email, $activation); //Line 95
$stmt->execute();
$stmt->close();
}
Output:
Before
After
Invalid request
MAMP Console:
[15-Apr-2011 15:09:10] PHP Warning: mysqli_stmt::bind_param() [<a href='function.mysqli-stmt-bind-param'>function.mysqli-stmt-bind-param</a>]: Number of elements in type definition string doesn't match number of bind variables in /Applications/MAMP/htdocs/Test/reg.php on line 95
The number is the same but I don't know why this error appears
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
Your "definition" string ("is") contains only two definitions, integer and string ... you should have 5 in there.
$stmt->bind_param("sssss", $name, $username, $password, $email, $activation);
... for example ...
You are only having five ? placeholders in your query, yet you're trying to bing six values to the query.
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
"is"
$name
$username
$password
$email
$activation
The format you are giving does only contain 2 definition, yet it must contain 5 to match your query. Try "sssss".
The "is" is the sixth variable, I suggest you remove this or add the field name in the statement:
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
Either remove from bind_param:
$stmt = $this->db->prepare("INSERT INTO users (name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param($name, $username, $password, $email, $activation);
or add to field names:
$stmt = $this->db->prepare("INSERT INTO users (**is**, name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("**is**", $name, $username, $password, $email, $activation);
or
$stmt = $this->db->prepare("INSERT INTO users (name, username, password,
email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("issss", $name, $username, $password, $email, $activation);

Categories