Trying to insert data into database PHP PDO - php

I've tried everything and just cant seem to get this working.. it's probably a silly mistake I can't see but any help is appreciated.
As stated in the question I'm trying to insert records into a table via a form. I have a functions.php which includes my database.php with the pdo connection (all working fine) class with the following function in it:
function insertStaffUser($username, $password, $role) {
include('database.php');
try {
$query = "INSERT INTO users (userid, username, password, role) VALUES (default, :username, :password, :role)";
$stmt->$db->prepare($query);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':role', $role);
$result = $stmt->execute();
if($result) {
echo "INSERTED SUCCESSFULLY";
} else {
echo "error inserting";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
And the following code is the one in my html class which is addUser.php with 3 text fields (new username, password and role).
<?php
if(isset($_POST['submit'])) {
$new_username = $_POST['username'];
$new_pass = $_POST['password'];
$new_role = $_POST['role'];
insertStaffUser($new_username, $new_pass, $new_role);
}
?>
Can anyone see what's wrong with this or what I'm doing wrong, thanks for the help!

Related

Unable to method chaining in MySQLi prepared statement using PHP

I am a beginner to PHP. I tried not to put $conn->prepare($sql_stmt) in one variable and just applied method chaining. But I got "Error while executing".
<?php
include_once 'dbh.inc.php';
if(isset($_POST['submit_btn']))
{
$fullname = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$sql_stmt = "INSERT INTO signup (name, username, passwrd) VALUES (?,?,?);";
//prepare and bind
$conn->prepare($sql_stmt)->bind_param("sss", $fullname, $username, $password);
//execute
if($conn->prepare($sql_stmt)->execute())
{
echo "User created";
}
else
{
echo "Error while executing";
}
}
else
{
echo "Unable to sign up.";
}
However if I instantiate $sql = $conn->prepare($sql_stmt) like below
<?php
include_once 'dbh.inc.php';
if(isset($_POST['submit_btn']))
{
$fullname = $_POST['name'];
$username = $_POST['username'];
$password = $_POST['password'];
$sql_stmt = "INSERT INTO signup (name, username, passwrd) VALUES (?,?,?);";
//prepare and bind
$sql = $conn->prepare($sql_stmt);
$sql->bind_param("sss", $fullname, $username, $password);
//execute
if($sql->execute())
{
echo "User created";
}
else
{
echo "Error while executing";
}
}
else
{
echo "Unable to sign up.";
}
It works and returns "User created". Why is that so?
Method chaining is not possible with mysqli. The return value of bind_param() is a boolean. It does not return self. You must call the methods like you showed in the second example:
$sql = $conn->prepare($sql_stmt);
$sql->bind_param("sss", $fullname, $username, $password);
$sql->execute();
In fact, mysqli is not very suitable to be used on its own in your application. If you want something simpler, then use PDO. If for some strange reason you must use mysqli, then you require some kind of abstraction layer that will prevent you from dealing with mysqli functions directly.
As of PHP 8.1, you can pass parameters directly in mysqli_stmt::execute(), which enables you to do method chaining in one line:
$sql = $conn->prepare($sql_stmt)->execute([$fullname, $username, $password]);
Also, please stop checking the return value of execute. You should enable mysqli error reporting instead. How to get the error message in MySQLi?

Doesn't insert data in DB

Almost 2 days my computer doesn't want to insert data in my DB, tried to change a lot in code but still not works. (and deleted ` - and nothing changed). Could you suggest what is the reazon?
<?php
include '../db.php';
try {
$stmt = $dbh->prepare(" INSERT INTO `users` (`login`,`password`) VALUES (:login, :password) ");
$stmt->bindParam(':login', $login );
$stmt->bindParam(':password', $password );
$_POST['login'] = $login;
$_POST['password'] = $password;
$stmt->execute();
}
catch (exeption $e) { // Если ошибка - показать сообщение об ошибке
echo $e->getMessage();
}
echo "\nPDO::errorCode(): ", $dbh->errorCode();
echo " ";
$rows = $stmt->fetchAll();
$num_rows = count($rows);
echo $num_rows;
/*header("location:../auth.php");*/
?>
Returns PDO::errorCode(): 00000 (thats fine), but it returns 0 rows! Maybe that's the reason
And my db.php file:
<?php
try { //Connecting to db via login and password
$user = 'mydatabases';
$pass = '1234';
$dbh = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass);
}
catch (exeption $e) { //if any mistakes show message of error
echo $e->getMessage();
}
?>
In my DB was 2 extra columns I wanted them to be empty (they didnt fill when user register), that was the reason why code didnt work and didnt send me any error messages

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.

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

Trying to take data from form and insert into database using PDO

I am trying to submit data from a form and have the data be inserted into my database using PDO. I am unsure what i am doing wrong at this point and could use any help that i can get.
Here is the code for connecting to my db
<?php
function connect(){
$config = array(
'$username' => 'root',
'$password' => 'root'
);
try {
$conn = new PDO('mysql:host=localhost;dbname=data', $config['$username'], $config['$password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'COME GET SOME IT WORKED!!!!';
}
catch(PDOException $e) {
print "Error!";
exit;
}
}
?>
Here is the code for handling the form data
<?php
// We will include connection file first
include('functions.php');
connect();
// check if varaibable is set and Add Rate Button pressed.
if(isset($_POST["submit"])){
echo 'COME GET SOME';
// Define Variables
$firstname = $_POST[firstName]; //firstName
$lastname = $_POST[lastName]; //LastName
$email = $_POST[emailAddress]; //Email Address
$age = $_POST[age]; //Age
// We Will prepare SQL Query
$STM = $dbh->prepare("INSERT INTO 'EmailList'(id, firstName, lastName, emailAddress, age) VALUES (NULL, :firstname, :lastname, :email, :age)");
// bind paramenters, Named parameters always start with colon(:)
$STM->bindParam(':firstname', $firstname);
$STM->bindParam(':lastname', $lastname);
$STM->bindParam(':email', $email);
$STM->bindParam(':age', $age);
// For Executing prepared statement we will use below function
$STM->execute();
// We use header here for redirecting it to other page where we will show success message.
header( "location:index.php");
}
?>

Categories