problems, custum wrap (class) around PDO, doesn't work - php

DB::construct();
$STH = DB::prepare('INSERT INTO users (username, password, email, activationkey) VALUES (?, UNHEX(?), ?, ?)');
var_dump($STH);
$result = $STH->execute(array('test', 'nils', 'test#mail.com', '227a038fe9c81515b514cb152188e95c'));
echo "working? <br />";
if($result == false) echo 'noooo...';
It outputs and doesn't put anything in the database. Works with a similare code with DPO just without my DB class. But I doesn't get any errors. Anyone have an idea what the problem could be?
object(PDOStatement)#2 (1) { ["queryString"]=> string(87) "INSERT INTO users (username, password, email, activationkey) VALUES (?, UNHEX(?), ?, ?)" }
working? <br /> noooo...

The code seems OK (ofcourse, don't know what you've done under the hood). Doesn't PDO itself generate an error / what does var_dump($STH->errorInfo()); say?

Related

bind_param doesn't replace ?s in my prepared statement

It registers the user successfully. But when I check it on my database, all of the values are 0s. What's the problem?
here's the function code:
public function insertUser($email, $firstName, $lastName, $encryptedPassword, $salt)
{
//SQL language - command to insert data
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (email=?, firstName=?, lastName=?, password=?, salt=?)";
//preparing SQL for execution by checking the validity
$statement = $this->conn->prepare($sql);
//if error
if (!$statement)
{
throw new Exception(($statement->error));
}
//assigning variables instead of '?', after checking the preparation and validity of the SQL command
$statement->bind_param('sssss', $email, $firstName, $lastName, $encryptedPassword, $salt);
//result will store the status/result of the execution of SQL command
$result = $statement->execute();
return $result;
}
The parameters for the function get set with the correct values when called, I tested it
I'm pretty new to PHP. If i correct my function, it doesn't create a new user. It doesn't even print out anything in the browser window. Here's the piece of code that calls this one (maybe it helps you with finding the solution):
$result = $access->insertUser($email, $firstName, $lastName, $encryptedPassword, $salt);
//result is positive
if ($result)
{
//throw back the user details
$return['status'] = '200';
$return['message'] = 'Successfully registered';
$return['email'] = $email;
$return['firstName'] = $firstName;
$return['lastName'] = $lastName;
echo json_encode($return);
$access->disconnect();
}
Your query is wrong.
//columns are declared here
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (email=?, firstName=?, lastName=?, password=?, salt=?)";
//you do not need to declare your columns again
Simple change your query to
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (?, ?, ?, ?, ?)";
Also, it appears as though you are storing your password and the salt separately, that tells me you are rolling your own hashing algorithm, there isn't really a need for this. I would remove your salt column, and use password_hash() for your password column.
remove the column=?
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (?, ?, ?, ?, ?)";
the code
column=?
in your value assignment is evalued as boolean condition that return false (0)

PDOStatement wrong result on check

I am having this code:
$PDOStatement = $pdo->prepare("INSERT INTO users (ID, email, password) VALUES(?, ?, ?)");
if($PDOStatement->execute($uuid, $email,$encrypted_password))
{
echo "test";
return true;
}
The data gets entered into the DB, but unforunetly the IF is not giving out the echo or the return.
Thanks in advance!
You need to pass the parameters as an array:
if($PDOStatement->execute($uuid, $email,$encrypted_password))
should be
if($PDOStatement->execute([$uuid, $email,$encrypted_password]))
(Manual: http://php.net/manual/en/pdostatement.execute.php)

Database not getting updated from php

I'm sending data from a form to a php script which should connect to a database and then update the table. It's basically a database of all registered users. For some reason, the database table is not getting updated with the values.
The form code is :
<body>
<div class="header">
Registration
</div>
<div class="content" style="text-align:center";>
<form name="input" action="success.php" method="post"><br>
First name: <input type="text" name="firstname"><br/>
Last name: <input type="text" name="lastname"><br/>
Age: <input type="text" name="age"><br/>
Date of Birth: <input type="text" name="dateofbirth"><br/>
Email: <input type="text" name="email"><br/>
<input type="submit" value="Submit"><br/><br>
</form>
</div>
<br><br><a href="index.html" style="font-size: 22px";>Back</a>
</body>
And the php code I have is:
<?php
$con=mysqli_connect("example.com","myname","123","database1");
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
mysqli_query($sql);
mysqli_close($con);
?>
Can someone please tell me where I'm going wrong?? The Database is not getting updated. There are no values being entered into my table.
Firstly, PLEASE use something like PDO or mySQLi's prepared statements.
Secondly, the database isn't getting updated because you need to concatenate (again, don't do this, please!) the values, like so:
$sql="INSERT INTO user (...) VALUES (".$_POST['firstname'].",".$_POST[]."...)";
This is very dangerous though, so I highly...highly recommend looking into PDO.
Also
The syntax for mysqli_query is wrong as stated in the comments on your post.
Try putting curly braces around the $_POST[...]
Like
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('{$_POST[firstname]}','...
change
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]','$_POST[dateofbirth]','$_POST[email]')";
to
$sql="INSERT INTO user
(fname, lname, age, dob, email) VALUES
('".$_POST['firstname']."','".$_POST['lastname']."','".$_POST['age']."','".$_POST['dateofbirth']."','".$_POST['email']."')";
Always check for errors when you run SQL statements. You'll never know what's going wrong unless you check whether the query was successful or not, and then print the error.
Also as other folks have commented, please don't include $_GET or $_POST variables directly in your SQL. This exposes you to getting hacked.
Here's an example of the proper way to code this:
<?php
$con=mysqli_connect("example.com","myname","123","database1");
if ($con->connect_error) {
trigger_error($con->connect_error, E_USER_ERROR);
}
$sql="INSERT INTO user (fname, lname, age, dob, email) VALUES (?, ?, ?, ?, ?)";
if (($stmt = $con->prepare($sql)) === false) {
trigger_error($con->error, E_USER_ERROR);
}
$stmt->bind_param("sssss", $_POST["firstname"], $_POST["lastname"],
$_POST["age"], $_POST["dateofbirth"], $_POST["email"]);
if ($stmt->execute() === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
$con->close();
?>
Now if there's a problem preparing or executing the query, it'll report it to you.
Create prepared statements is not that hard. Simply copy paste and you are good. I added some extra security with escapeshellarg, which should be more used then it is since prepared statements isn't always 100% secure.
<?php
$firstname = escapeshellarg($_POST["firstname"]);
$lastname = escapeshellarg($_POST["lastname"]);
$age = escapeshellarg($_POST["age"]);
$dateofbirth = escapeshellarg($_POST["dateofbirth"]);
$email = escapeshellarg($_POST["email"]);
$con=mysqli_connect("example.com","myname","123","database1");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_stmt_init($con);
$query = "INSERT INTO user (fname, lname, age, dob, email) VALUES (?, ?, ?, ?, ?)";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, "sssss", $firstname, $lastname, $age, $dateofbirth, $email);
if(mysqli_stmt_execute($stmt))
{
mysqli_close($con);
}
?>
Note that "sssss" stands for Strings. If your age is an int variable then use "ssiss" instead.
PS. A simple mistake I had once with WAMP (Apache) was that the user didn't have the right privileges. It took me way too many hours to find that, don't do the same mistake ;)
Tested
I created a table with the same entries that you posted and have come to this conclusion.
But first; as others have pointed out and it's been said time and time again, the use of MySQL_ is being deprecated and will be deleted in the very near future. Therefore using MySQLi_ and/or PDO is strongly and highly recommended.
To quickly fix your problem, you are not telling it to connect to your DB when passing query.
Change:
mysqli_query($sql);
to:
mysqli_query($con, $sql);
and it will work. It worked for me, therefore theoretically it will work for you also.
I suggest you use Bill Karwin's version for better security.

Mysqli Procedural Insert Into Table not working

I am trying to insert into a table with Procedural Mysqli. It is not posting any errors nor is it posting the information to the database. Here is my code:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES ({$_POST['FirstNameTbx']}, {$_POST['LastNameTbx']}, {$_POST['UsernameTbx']}, {$_POST['PasswordTbx']}, {$_POST['AccessDDL']})";
mysqli_query($link, $query);
mysqli_close($link);
$Error .= "$query";
Update:
I changed to prepared statement, now I am getting:
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in /home/bryantrx/public_html/ec/add_user.php on line 19
There are only 5 variables that need to be bound, and the UserID auto increments, so it doesn't need to be bound or referenced in the statement..
if ($stmt = $link->prepare("INSERT INTO Accounts (FirstName, LastName, Username, Password, Access) VALUES (?, ?, ?, ?, ?)")){
$stmt->bind_param($_POST['FirstNameTbx'], $_POST['LastNameTbx'], $_POST['UsernameTbx'], $_POST['PasswordTbx'], $_POST['AccessDDL']);
$stmt->execute();
$Error .= "success";
$stmt->close();
} else {
echo $link->error;
}
To get an error message you need to call mysqli_error:
$error = mysqli_error($link);
You would also make life easier (and more secure) for yourself if you built your queries using prepare and parameters:
$query = "INSERT INTO Accounts (FirstName, LastName, Username, Password, Access)
VALUES ( ?, ?, ?, ?, ?)";
if ($stmt = mysqli_stmt_prepare($link, $query)) {
mysqli_stmt_bind_param($stmt, "sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);
if (!mysqli_stmt_execute($stmt)) {
$error = mysqli_stmt_error($stmt);
}
mysqli_stmt_close($stmt);
} else {
$error = mysqli_error($link);
}
mysqli_close($link);
UPDATE - ok, you've swapped to OO which is fine. When using bind_param the first parameter describes the data you are binding. In this case if it is five strings, you would put 5 "s" like so:
$stmt->bind_param("sssss",
$_POST['FirstNameTbx'],
$_POST['LastNameTbx'],
$_POST['UsernameTbx'],
$_POST['PasswordTbx'],
$_POST['AccessDDL']);

MySQL db not updating from form with php processing

Using the code
# the data we want to insert
$data = array($first_name, $last_name, $email_from, $telephone, $dateofbirth, $addresslone, $addressltwo, $townnm, $countynm, $typeapp, $issubscribed);
$STH = $dbh->prepare("INSERT INTO members (fname, sname, email, phone, dob, addressl1, addressl2, town, county, type, subscribed) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$STH->execute($data);
?>
<!--<!DOCTYPE html>
<head><title></title></head><body> commented out during testing -->
Thank you for contacting us We will be in touch with you very soon.
<!-- </body></html> -->
The user is presented with the success message:
Thank you for contacting us We will be in touch with you very soon.
There are no php errors recorded.
This is to insert into this database
Error reporting is in the form of the PDO try catch:
catch(PDOException $e)
{
echo $e->getMessage();
}
Despite it looking as if it is working perfectly, however, the database seems unable to receive updates. :/
As per your database structure screenshot, table name is member and you used members into your insert query

Categories