I have been trying to insert data from a json file into mysql through php.
I have a function doing the insert in one file, while the decoding is done in another file.
When I run the code, I recieve this error:
You could not be registered due to a system error. We apologize for any inconvenience.
Column 'password' cannot be null
Query: INSERT INTO users (id, email, password, username, deviceId, date_created) VALUES (null, ?, ?, ?, ?, NOW() )
Query was executed
enter code here
Here are my three files:
insertion.php:
//Require files
require('functions.php');
if(file_exists('data.json')){
echo "The file exists ";
$file= file_get_contents('data.json');
echo json_encode('data.json');
$data=json_decode($file, true);
var_dump($data);
$email= $data["email"];
$password= $data["password"];
$username= $data["username"];
$deviceId= $data["deviceId"];
$tableName= 'users';
$email= "email#example.com";
$error=json_last_error();
echo "<br><br>";
echo "your email shoudl be displayed right here: ".$email. "This is email";
echo "<br>JSON Errors will display here:". $error;
$execute= dataInsert($tableName, $email, $password, $username, $deviceId);
if($execute){
echo "Query was executed";
}
}
else{
echo "file does not exist";
}
functions.php:
//------------------------dataInsert()---------------------------//
function dataInsert($tableName, $email, $password, $username, $deviceId){
//set database connection
require('mysqli_connect.php');
if($dbc){
echo "<h3>connection successful</h3>";
}
//form query using the values and tablename
$query = "INSERT INTO users (id, email, password, username, deviceId, date_created)
VALUES (null, ?, ?, ?, ?, NOW() )";
//Prepare statement
$stmt= mysqli_prepare($dbc, $query);
//Bind the variables
mysqli_stmt_bind_param($stmt, 'sssi', $email, $password, $username, $deviceId);
//Execute the query
$result=mysqli_stmt_execute($stmt);
if($result){
echo "Success !";
}
else{
// Public message:
echo 'System Error
<p class="error">You could not be registered due to a system error. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbc) . '<br /><br />Query: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the database connection.
return true;
}
data.json
<pre>
<code>
{"users":[
{
"email":"fakeemail#gmail.net",
"password":"mypass12",
"username":"myusername",
"deviceId":"21"
}
]}
When I use var_dump to display the json array, it looks correct:
"data.json"array(1) { ["users"]=> array(1) { [0]=> array(4) { ["email"]=> string(19) "fakeemail#gmail.net" ["password"]=> string(6) "mypass12" ["username"]=> string(13) "myusername" ["deviceId"]=> string(2) "21" } } }
I've been able to insert rows into the database, but they were all blank, besides the date, and auto increment id. When I set $email= email#example.com it will display the password cannot be null, but commenting that line out will cause the error to display 'email' cannot be null
You are inserting null into your ID field. Try removing that.
You are accessing the values of the decoded json string wrongly, passing true as the second value of json_decode you get one associative array.
var_dump($data['users'][0]['email']);
Result
fakeemail#...
So you could do something like
if (count($data['users']))
{
foreach($data['users'] as $user)
{
// insert query passing
// $user['email'], $user['password'],
print $user['email'];
}
}
Related
I want to create a simple piece of code that will put data into the database form a PHP script, everything works fine except putting the data into the database! (I am running a server with PHP7)
The output of the affected rows shows -1 (strange), I double checked my code, compared it with others, tried searching for a common issue on the internet, even tried on a local server with no avail.
You can see it here:
https://leer.bosvision.nl/register.php
My code:
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = 'INSERT INTO users_two (ID, username, password) VALUES (1, gfd, gfd)';
if(mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
To quote the documentation:
-1 indicates that the query returned an error.
And your insert statement indeed errors out, since you don't have a gfd column. If you meant to use that as a value, it should be surrounded by single quotes:
$query = "INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')";
# Here -------------------------------------------------------------^---^--^---^
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = "INSERT INTO users_two (username, password) VALUES ('gfd', 'gfd')";
if($result= mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
One assumes ID is auto increment, so that doesn't need to be in there, or is it not and the issue you are encountering is that its a duplicate entry for key. Also you need to wrap your var data in ' '
I would guess that this is an SQL issue. Can you run your query directly on your database? That would give you the error.
Read this page for more info: PHP insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Normally you shouldn't be inserting an ID yourself because it should be auto increment.
try adding quotes to the string values, as in:
"INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')"
EDIT: Seems to be something with the database. We cant figure out what it is.
Im having a problem with storing data thats been put into the forms. I tested the query in MS SQL (we have to use that for school) but it doesnt seem to work once i put in my variables. So im guessing the problem comes from the variables. However im not sure about that because when i echo the $_POST variables it outputs strings like i want it to. But when i put it in the query it just wont store rit in my database. Would be great if someone could help me out with this.
HTML code:
<form action="registerSystem.php" method="post">
Email:
<input type="email" name="emailAdres" required> <br>
Naam:
<input type="text" name="naamGebruiker" required> <br>
Wachtwoord:
<input type="password" name="wachtwoordGebruiker" required> <br>
Herhaal wachtwoord:
<input type="password" name="bevestigWachtwoord" required> <br>
<input type="submit" value="Registreer">
</form>
Php code:
require "connect.php";
session_start();
GLOBAL $conn;
function createAccount(){
$email = $_POST['emailAdres'];
$username = $_POST['naamGebruiker'];
$wachtwoord = $_POST['wachtwoordGebruiker'];
GLOBAL $conn;
$hashed_pass = md5($wachtwoord);
$paypal = $email;
$subscription_start = date("Y:m:d");
$land = 'Nederland';
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name) "
."VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$conn->query($query);
}
if($_SERVER['REQUEST_METHOD'] === 'POST'){
//password check
if ($_POST['wachtwoordGebruiker'] == $_POST['bevestigWachtwoord']) {
createAccount();
header("location: loginSystem.php");
} else {
echo "De opgegeven wachtwoorden komen niet overeen!";
}
}?>
I have found where the problem is on your function.
The problem is here : VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
that null after :subscription_start is the problem, rather put a place holder in place then have a string that you will assign it value to null. then your query should work.
I'm not sure what datatype is subscription_end but I guess it should be date. and also use try catch block so that you can see when you have errors in your sql query. Also don't rush to reload the next page after running your query atleast but some delay on your header() so that you can print success message and see if its displaying then load next page
So this is how I updated your function.
<?php
require 'connect.php';
session_start();
GLOBAL $conn;
function createAccount()
{
$email = $_POST['emailAdres'];
$username = $_POST['naamGebruiker'];
$wachtwoord = $_POST['wachtwoordGebruiker'];
GLOBAL $conn;
$hashed_pass = md5($wachtwoord);
$paypal = $email;
$subscription_start = date("Y:m:d");
$land = 'Nederland';
$enddate = 'null';
try {
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name) " . "VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, :enddate, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->bindParam(':enddate', $enddate);
if ($query->execute()) {
echo "Done";
}
}
catch (PDOException $e) {
echo "error". $e->getMessage();
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//password check
if ($_POST['wachtwoordGebruiker'] == $_POST['bevestigWachtwoord']) {
createAccount();
header("refresh:5;url=loginSystem.php");
} else {
echo "De opgegeven wachtwoorden komen niet overeen!";
}
}
?>
Hope this helps.
NB: Don't use md5(); to encrypt your passwords its no longer safe,
rather use php functions password_hash() and password_verify()
they are available on php.net for you to read and understand them.
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name)"
." VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->execute();
What I've changed here is $conn->query($query); to $query->execute(). Because you're working with prepared statements, you need to call execute method of the object instance of prepared statement $query.
$conn->query($sql) is commonly used when only retrieving results with SELECT query which doesn't contain filtering conditions that receive data from user inputs.
For your information, as a best practice, wrap up the code with try catch blocks which helps you handle the errors.
try {
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name)"
." VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->execute();
} catch (PDOException $ex) {
echo $ex->getMessage(); // or die($ex->getMessage());
}
Before using try catch blocks, set the PDO's error reporting to exception:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Set this attribute as soon as you created the PDO object instance.
You can also set this attribute during the object instantiation through constructor like:
$conn = new PDO('mysql:host=localhost;dbname=demo', 'root', 'password', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
Hope it helps!
I have this error:
Call to a member function bind_param() on a non-object
in /home/ccraft50/public_html/C-Blog/InsertDataPosts.php on line 15
<?php
$servername2 = "localhost";
$username2 = "My DB";
$password2 = "My Pass";
$dbname2 = "My DB";
// Create connection
$dbconn2 = new mysqli($servername2, $username2, $password2, $dbname2);
// Check connection
if ($dbconn2->connect_error) {
die("Connection failed: " . $dbconn2->connect_error);
}
$insIndexData = $dbconn2->prepare("INSERT INTO " . str_replace(str_split('\\/:*?"<>|.$+-%##!~&;\',=~` '), "_", $_POST['filename']) . "_Index (SubjectName, IndexData) VALUES (?, ?)");
$str_prot_index = array('<script>', '</script>', '<?php', '?>', '<html', '</html>', '<body', '</body>', '<head', '</head>', '<pre', '</pre>', '<div', '</div>');
$insIndexData->bind_param('ss', $_POST['filename'], str_replace($str_prot_index, '', $_POST['comment']));
$insIndexData->execute();
$insIndexData->close();
if($dbconn2->prepare($insIndexData)) {
echo "Successfuly Insert data for index!";
} else {
echo "Error: " . $dbconn2->error;
}
$dbconn2->close();
?>
You are using a database wrong way.
A database have to consist of tables, each holding multiple rows. While you apparently want to create a distinct table for each file. Instead, you have to store all your files in a single table, adding a filename as a field, not a table name.
$stmt = $dbconn2->prepare("INSERT INTO files (SubjectName, IndexData) VALUES (?, ?)");
$stmt->bind_param('ss', $_POST['filename'], $_POST['comment']);
$stmt->execute();
echo "Successfuly Insert data for index!";
Note that the second part of code which is preparing the same query in a second time makes no sense. To test whether the insert were successful or not, you have to add this line before new mysqli(:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
And it will throw an error if insert fails.
Your prepare is failing. Try to add some testing to make sure its preparing correctly. After you ->prepare
if($insIndexData !== false)
{
etc...
I have written a form with server side validation using php and now my aim is to insert all the input's from my form into my database (which already has its tables). Below is my syntax:
//Example of one of my validations (for postcode input)
if (empty($_POST["postcode"])) {
$postcodeErr = "";
} else {
$postcode = test_input($_POST["postcode"]);
if(!preg_match("/^[0-9]*$/", $postcode)) {
$postcodeErr = "Only numeric characters";
}
else if (strlen($postcode) != 4) {
$postcodeErr = "Must be 4 digits in length";
}
}
}
//Connect to database server
$conn = mysql_connect("localhost", "-----", "------");
mysql_select_db("-------", $conn)
or die ('Database not found ' . mysql_error() );
// The SQL statement is built
$sql = "INSERT INTO Customer (name, address, suburb, state, postcode)
VALUES ('$_POST[name]', '$_POST[address]', '$_POST[suburb]', '$_POST[$state]', '$_POST[postcode]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn)
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //end of my php tag
When I run my form, I get a parse error saying that I have an unexpected T_FUNCTION. I know there is a lot above (tried to make it as simple as I can) but I can't seem to word around fixing the error and if I do, I just get another error. Am I writing the code correctly? Normally it's best when other people look at your work. Help will be much appreciated!
The quotes for $_POST['name'] and all other variables was missing in the post variable.
Try with
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$sql = "INSERT INTO Customer (name, Address, suburb, state, postcode)
VALUES ('$name', '$address', '$suburb', '$state', '$postcode')";
you also have one extra brace above database connection, use mysqli prepared statements for better security.
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "failed to connect to the database"; die();
}
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$stmt = $db->prepare("insert into `Customer` (name, Address, suburb, state, postcode) VALUES (?,?,?,?,?)";
$stmt->bind_param('sssss', $name, $address, $suburb, $state, $postcode);
$stmt->execute();
echo $stmt->affected_rows."record added";
mysql_close($conn) Needs to have a ; after it...
That's why the function after it is unexpected
Agreed with Fred, there seems to be an extra ending brace just above //Connect to database server which is breaking the code.
If that doesn't fix it, please copy/paste your full error message.
EDIT:
else if (strlen($postcode) != 4) {
needs to be
} else if (strlen($postcode) != 4) {
And there are two extra braces at the end of that if statement (just above the //Connect to database server)
I'm trying to grab the id after a query using mysql_insert_id();, but I'm still getting 0 despite the fact that
I've placed it after the query itself and
I've made sure that the id (called P_Id) has AUTO_INCREMENT.
Code below:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
$idit = mysql_insert_id();
echo $idit;
if (mysqli_query($con,$sql))
{
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Thinking "Oh okay maybe I have to actually query it first", I did the following but came up with the same result:
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
if (mysqli_query($con,$sql))
{
$idit = mysql_insert_id();
echo $idit;
}
else
{
echo "Error message goes here: " . mysqli_error($con);
}
Any idea where I went wrong? I've gone through other threads but nothing seems to be working for me. Thanks in advanced.
EDIT: I have changed mysql_insert_id(); to mysqli_insert_id(); and this time it didn't even return a 0, just blank.
EDIT 2: Thank you mbouzahir - your solution worked :)
Tried using mysqli_insert_id($con) instead of mysql_insert_id() in your second example?
Your query is vulnerable to SQL injection. You should be using prepared statements with parameter binding. Try this (and yes, I'm using the OOP API because it's a damn site cleaner)
$con = new mysqli(-connectiondetails-);
if ($con->connect_errno) {
throw new Exception($con->connect_error, $con->connect_errno);
}
$stmt = $con->prepare(
'INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
if ($stmt === false) {
throw new Exception($con->error);
}
// you should probably check here that all required POST params are present
$stmt->bindParam('sssssssssss',
$_POST['name'],
$_POST['email'],
$_POST['address'],
$_POST['phone'],
$_POST['date'],
$_POST['service'],
$_POST['extra1'],
$_POST['extra2'],
$_POST['extra3'],
$_POST['extra4'],
$_POST['extra5']);
if (!$stmt->execute()) {
throw new Exception($stmt->error);
}
echo $con->insert_id;
Try this one
$con=mysqli_connect(-connectiondetails-);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO clients (Name, Email, Address, Phone, Date, Service, ExtraOne, ExtraTwo, ExtraThree, ExtraFour, ExtraFive) VALUES ('$_POST[name]','$_POST[email]','$_POST[address]','$_POST[phone]','$_POST[date]','$_POST[service]','$_POST[extra1]','$_POST[extra2]','$_POST[extra3]','$_POST[extra4]','$_POST[extra5]')";
if (mysqli_query($sql,$con))
{
$idit = mysqli_insert_id();
echo $idit;
}
else
{
echo "Error message goes here: " . mysql_error($con);
}