Issue in store user details in sql database - php

I have created register form page using php.
This is code_exec.php:
<?php
include 'config.php';
error_reporting(E_ERROR);
session_start();
$form = $_POST;
$fname=$form['fname'];
$lname=$form['lname'];
$email=$form['email'];
$pass=$form['pass'];
$phone=$form['phone'];
$sex_select=$form['sex_select'];
$month=$form['month'];
$day=$form['day'];
$year=$form['year'];
$result = "INSERT INTO crop ( fname, lname, email, pass, phone,`sex_select`, month,day,year) VALUES
( :fname, :lname, :email, :pass, :phone, :sex_select, :month, :day, :year)";
if (!$result) {
die(msg(0,"wrong query"));
}
?>
config.php:
<?php
$user = 'root';
$pass = '';
$db = new PDO( 'mysql:host=localhost;dbname=crop', $user, $pass );
?>
Now i didn't show any error, but didn't store user data.
May i know, what is my mistake with my code.
Thanks in advance.

Remove the field "year" from your table and rename it to something else.As mysql treats the year like a keyword .so it will not allow you to insert data into the table.
The same problem was raised for me few days back. I have tested in phpmyadmin.I found this solution.
And Also you need to execute the query like this
mysql_query($result);
then check if it is not executed..

you need to try like this
include 'config.php';
error_reporting(E_ERROR);
session_start();
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$email=$_POST['email'];
$pass=$_POST['pass'];
$phone=$_POST['phone'];
$sex_select=$_POST['sex_select'];
$month=$_POST['month'];
$day=$_POST['day'];
$year=$_POST['year'];
$result = $db->prepare("INSERT INTO crop (`fname`, `lname`, `email`, `pass`, `phone`,`sex_select`, `month`,`day`,`year`) VALUES ( :fname, :lname, :email, :pass, :phone, :sex_select, :month, :day, :year)");
$result->bindValue(':fname', $fname, PDO::PARAM_STR);
$result->bindValue(':lname', $lname, PDO::PARAM_STR);
$result->bindValue(':email', $email, PDO::PARAM_STR);
$result->bindValue(':pass', $pass, PDO::PARAM_STR);
$result->bindValue(':phone', $phone, PDO::PARAM_STR);
$result->bindValue(':sex_select', $sex_select, PDO::PARAM_STR);
$result->bindValue(':month', $month, PDO::PARAM_STR);
$result->bindValue(':day', $day, PDO::PARAM_STR);
$result->bindValue(':year', $year, PDO::PARAM_STR);
$result->execute();

Related

Insert PHP form in PostgresSQL database

So i'm building a website where you can buy tickets etc. So I want to have a login system, I started building the website and started with the PHP code to sign in but I always get the error Array?? It does work when I only want to insert a variable email and the rest plain text.
I've spend a whole week trying different methods etc. But I don't get why it doesn't work.
I even get the same error when I use constants instead of POST variables...
CREATE TABLE Users(
userId SERIAL,
email VARCHAR(40) NOT NULL,
password VARCHAR(30) NOT NULL,
firstName VARCHAR(20) NOT NULL,
lastName VARCHAR(20) NOT NULL,
age INT NOT NULL,
organizer BOOLEAN NOT NULL,
region VARCHAR(30),
favouriteGenre VARCHAR(15),
description VARCHAR(200),
PRIMARY KEY(userId)
);
<?php
require 'globals.php';
try {
$db_conn = new PDO("pgsql:host=$db_host;dbname=$db_name", $db_user, $db_password);
} catch (PDOException $e) {
die("Error: ".$e->getMessage()."\n");
}
$email = $_POST['email'];
$password = $_POST['password'];
$pwdConfirm = $_POST['confirm'];
$firsName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$age = $_POST['age'];
$rol = $_POST['rol'];
$region = $_POST['region'];
$favGenre = $_POST['favGenre'];
$description = $_POST['description'];
//TODO inputChecks
$query = $db_conn->prepare('INSERT INTO users (email, password, firstName, lastName, age, organizer)
VALUES (:email, :password, :firstName, :lastName, :age, :organizer)');
$query->bindParam(':email', $email, PDO::PARAM_STR, 40);
$query->bindParam(':password', $password, PDO::PARAM_STR, 30);
$query->bindParam(':firstName', $firstName, PDO::PARAM_STR, 20);
$query->bindParam(':lastName', $lastName, PDO::PARAM_STR, 20);
$query->bindParam(':age', $age, PDO::PARAM_INT);
$query->bindParam(':organizer', $firstName, PDO::PARAM_BOOL);
if ($query->execute()) {
echo "success!";
} else {
die("Execute query error: ".$db_conn->errorInfo());
}
$db_conn = NULL;
I expect it to insert it into the database and don't give an error anymore.
Try this
$query = $db_conn->prepare('INSERT INTO users (email, password, firstName, lastName, age, organizer,region, favouriteGenre, description)
VALUES (:email, :password, :firstName, :lastName, :age, :organizer, :region, :favouriteGenre, :description)');
$query->bindParam(':email', $email, PDO::PARAM_STR, 40);
$query->bindParam(':password', $pwd, PDO::PARAM_STR, 30);
$query->bindParam(':firstName', $firstName, PDO::PARAM_STR, 20);
$query->bindParam(':lastName', $lastName, PDO::PARAM_STR, 20);
$query->bindParam(':age', $age, PDO::PARAM_INT);
$query->bindParam(':organizer', $firstName, PDO::PARAM_BOOL);
$query->bindParam(':region', $region, PDO::PARAM_STR);
$query->bindParam(':favouriteGenre', $favGenre, PDO::PARAM_STR);
$query->bindParam(':description', $description, PDO::PARAM_STR);
One of the possible causes of the error you are getting is that you are trying to insert 6 values into a table with 9 fields.Another possible cause of the bug is that you have defined the variable for password as $pwd but use $password variable when binding parameters.

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.

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

Not being able to Insert data into MYSQL tables using PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am trying to insert data into MySQL tables but I am not sure why it is not working
<?php
include 'connect.php';
$userName = $_POST['name'];
$firstname = $_POST['FirstName'];
$Surname = $_Post['Surname'];
$email = $_POST['EmailAddress'];
$password = $_POST['Password'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`)
VALUES ('.$userName.','.$password.','.$firstname.','.$Surname.', '.$gender.', '.$dob.', '.$email.')';
$stmt = $conn->prepare($query);
try {
$myarray = array(
":userName" => $userName,
":password" => $password,
":firstname" =>$firstname,
":Surname" => $Surname,
":gender" => $gender,
":dob" => $dob,
":email" => $email);
print_r($myarray);
$stmt->execute($myarray);
} catch(PDOException $err) {
echo "Houston we have a problem: $err";
}
?>
Please tell me if I am doing something wrong.
You're using Prepared Statements wrong. With $db->prepare() you're actually submitting the query with placeholders and not with the values (called sending a template). In your case:
$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`)
VALUES (:userName, :password, :firstname, :Surname, :gender, :dob, :email)';
First make sure you have connected to the sql properly then change your codes to this one:
$table='User';
$sql="INSERT INTO
$table(username,Password,First Name,Surname,Gender,DOB,Email Address) VALUES ('$userName','$password','$firstname','$Surname', '$gender', '$dob', '$email')";
$result=$conn->query($sql) ;
Good Luck!
use this one for connection :
$db = "mysql:host=yourhost;dbname=yourdbname";
$username = " ";
$password = " ";
$conn = new PDO( $db, $username, $password ) or die("Error Connection !! ");
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8");
Try this approach:
<?php
include 'connect.php';
$userName = $_POST['name'];
$firstname = $_POST['FirstName'];
$Surname = $_Post['Surname'];
$email = $_POST['EmailAddress'];
$password = $_POST['Password'];
$gender = $_POST['Gender'];
$dob = $_POST['DOB'];
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'INSERT INTO `User` (`username`,`Password`,`First Name`,`Surname`, `Gender`, `DOB`, `Email Address`)
VALUES (:userName, :password, :firstname, :Surname, :gender, :dob, :email)'
try {
$stmt = $conn->prepare($query);
$result = $stmt->execute(array(
":userName" => $userName,
":password" => $password,
":firstname" =>$firstname,
":Surname" => $Surname,
":gender" => $gender,
":dob" => $dob,
":email" => $email));
if ($result) {
// success!
echo 'lastInsertId = '.$conn->lastInsertId();
} else {
// Query failed.
echo 'errorcode = '.$stmt ->errorCode();
}
} catch(PDOException $err) {
echo "Houston we have a problem: $err <br />";
echo 'errorcode = '.$stmt ->errorCode();
}

PHP PDO Error while executing and inserting in cleardb

Hi I am getting error during the execution of PDO prepare statement. My local development works fine but when I try to insert to cleardb in cloud this error occur:
SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user 'b2218f51d4a66e'#'191.235.136.58' for table 'user'' in /var/www/php1/CRUD.php:52
function create_User($firstname, $lastname, $username, $password, $address, $city, $zip, $country, $email) {
global $dbh;
$this->password = $password;
$token = md5($this->salt1 . $this->password . $this->salt2);
$this->sth = $dbh->prepare('INSERT INTO `Php_Project`.`User`
(
userName,
passWord,
create_DateStamp,
e_mail)
VALUES
(
:username,
:token,
NOW(),
:email
);
');
$this->sth->bindParam(':username', $username, PDO::PARAM_STR);
$this->sth->bindParam(':token', $token, PDO::PARAM_STR);
$this->sth->bindParam(':email', $email, PDO::PARAM_STR);
if ($this->sth->execute()) {
$this->message = "true";
} else {
$this->message = "false";
}
if ($this->message == "true") {
$userId = $dbh->lastInsertId();
$this->sth = $dbh->prepare('INSERT INTO `Php_Project`.`user_Detail`
(
firstName,
lastname,
adress,
zip,
city,
country,
userId)
VALUES
(
:firstname,
:lastname,
:address,
:zip,
:city,
:country,
:userId
);');
$this->sth->bindParam(':firstname', $firstname, PDO::PARAM_STR);
$this->sth->bindParam(':lastname', $lastname, PDO::PARAM_STR);
$this->sth->bindParam(':address', $address, PDO::PARAM_STR);
$this->sth->bindParam(':zip', $zip, PDO::PARAM_INT);
$this->sth->bindParam(':city', $city, PDO::PARAM_STR);
$this->sth->bindParam(':country', $country, PDO::PARAM_STR);
$this->sth->bindParam(':userId', $userId, PDO::PARAM_STR);
if ($this->sth->execute()) {
$this->message = true;
} else {
$this->message = false;
}
}
}
This is a permissions problem. Your database user has the INSERT permission for the table on your development server but not on your production server, so you'll need to change the user permissions using GRANT on your production server.

Categories