I have a PHP function that checks some data before inserting it into the DB.
For now I have thees messages that inside my php function that display, wherever I am calling the function. ex: div.
I would like instead of the small message inside the div, to have a message box that will display the message. How can I do this? Thanks
if($u_l_name == $dbuser_last_name and $u_name == $dbuser_first_name)
{
echo "Record Exists Already";
}
else
{
$stmt2 = $this->link->prepare("INSERT INTO employers (user_password, user_first_name, user_last_name, user_DOB, user_address, user_email, user_phone, user_gender, user_position, user_contract_type, user_contract_hours) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt2->bind_param("ssssssssssi", $u_password, $u_name, $u_l_name, $u_DOB, $u_address, $u_email, $u_phone, $u_gender, $u_position, $u_contract_type, $u_contract_hours);
$stmt2->execute();
$stmt2->close();
echo "Record Added Succesfully";
}
Function call:
<?php
if(isset($_POST['submitButton']))
{
$admin_query->addEmployerData($u_password, $u_name, $u_l_name, $u_DOB, $u_address, $u_email, $u_phone, $u_gender, $u_position, $u_contract_type, $u_contract_hours);
}
?>
Do you mean Javascript alert method? if yes here is how you can do it:
$message;
if($u_l_name == $dbuser_last_name and $u_name == $dbuser_first_name)
{
$message = "Record Exists Already";
}
else
{
$stmt2 = $this->link->prepare("INSERT INTO employers (user_password, user_first_name, user_last_name, user_DOB, user_address, user_email, user_phone, user_gender, user_position, user_contract_type, user_contract_hours) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt2->bind_param("ssssssssssi", $u_password, $u_name, $u_l_name, $u_DOB, $u_address, $u_email, $u_phone, $u_gender, $u_position, $u_contract_type, $u_contract_hours);
$stmt2->execute();
$stmt2->close();
$message = "Record Added Succesfully";
}
echo "<script>alert('$message')</script>";
Related
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'];
}
}
the problem is..i try to parsing json from php..here is jquery code:
$.post( "confirmsignup.php", $("#signupform").serialize()).always(function( data ) {
alert(data.msg);
}, "json");
PHP code:
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!($query_run = mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
?>
{
"msg": "<?php echo $msg ." - ". $query; ?>"
}
secureing() is for returning string after escape_string..
$msg suppose to return string "complete"... but it returning "error"..
however in phpmyadmin, query is successfully executed..
i think there is no mistake..what is my mistake?please help..
Can you please change the following code with your code, I have used mysql_insert_id to check record is inserted or not.
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
$query_run = mysql_query($query);
$id = mysql_insert_id();
if($id > 0)
{
$msg = "complete";
}
else
{
$msg = "error";
}
It may help you.
I have same issue long time ago!
it's because you haven't any AI primary key in the table!
add a field like this to the table: id INT Primary Key Auto Increment.
this will works!
and migrate to mysqli or pdo for better security and support! ;)
try my code is seem you have put wrong condition
if (isset($_POST['gender'])&&isset($_POST['fname'])&&isset($_POST['sname'])&&isset($_POST['username'])&&isset($_POST['dob'])) {
$gender=secureing($_POST['gender']);
$fname=secureing($_POST['fname']);
$sname=secureing($_POST['sname']);
$username=secureing($_POST['username']);
$email=secureing($_POST['email']);
$dob=secureing($_POST['dob']);
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$pass=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '".md5($pass)."', '$dob')";
if(!(mysql_query($query))){
$msg = "error";
}else{
$msg = "complete";
}
}
}
}
i just found the solution, after change my php API to connecting to database.
from:
if(!#mysql_connect('localhost', 'root', '')||!#mysql_select_db('knewit')){
die("something not right");
}
to:
$mysqli = new mysqli("localhost", "root", "", "knewit");
after that, i change my executing method from mysql_query to $mysqli->query.
i also change my jquery post method from always to done.
and the final code be like this.
jQuery script:
$.post( "confirmsignup.php", $("#signupform").serialize()).done(function( data ) {
alert(data.msg);
}, "json");
PHP script:
if (isset($_POST['agree'])&&isset($_POST['pass'])&&isset($_POST['repass'])) {
$passs=secureing($_POST['pass']);
if ($_POST['pass']==secureing($_POST['repass'])) {
$query = "INSERT INTO users VALUES('$username', '$gender', '$fname', '$sname', '$email', '$passs', '$dob')";
if(!($query_run = $mysqli->query($query))){
$msg = "error";
}
else
{
$msg = "complete";
}
}
}
}
header('Content-Type: application/json');
$arrayName = array('msg' => $msg );
echo json_encode($arrayName);
thank you for answer my question. i really appreciate it.
I'm new to php.I'm trying to build a signup webpage in which if email entered doesn't exist it should insert the values entered.The code works fine and it returns successful when a new mail is entered.But the problem is when I check my database the new values are not inserted.Is there any mistake in my code?
Thanks in advance.
<?php
session_start();
if(isset($_POST['signup'])){
include_once("db.php");
$email=strip_tags($_POST['emailid']);
$username=strip_tags($_POST['username']);
$password=strip_tags($_POST['password']);
if($email==NULL || $username== NULL || $password==NULL){
print "Missing one of the fields";
}
else{
$email=stripslashes($email);
$username=stripslashes($username);
$password=stripslashes($password);
$email=mysqli_real_escape_string($db,$email);
$username=mysqli_real_escape_string($db,$username);
$password=mysqli_real_escape_string($db,$password);
$query = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($db,$query);
if($result && mysqli_num_rows($result) > 0 )
{
echo "Account already exists.Please login";
}
else{
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";
}
else
{
echo "Error";
}
}
}
}
?>
You are not executing the insert query, it should look like:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
$sql= mysqli_query($db,$sql); ///You are missing this
Change from:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if($sql)
{
echo "Account created successfully.";
}
To:
$sql="INSERT INTO user (ID,email,username,password) VALUES
(NULL,'$email','$username','$password')";
if(mysqli_query($db,$sql))
{
echo "Account created successfully.";
}
You need to execute the 2nd query ($sql)
$sql="INSERT INTO user (email,username,password) VALUES
('$email','$username','$password')";
if(mysqli_query($db,$sql))
{
echo "Account created successfully.";
}
Remove the null INSERT value it's not needed and should be auto generated if auto-incremental index.
execute the $sql statement a a MySQLi_query and then use the result of that in the IF statement.
Bonus: Use mysqli_error($db) to feed you back errors you will encounter, such as:
mysqli_query($db,$sql) or die("error: ".mysqli_error($db));
I am wondering how can I insert the values retrieved from a HTML form into 2 tables, loginDetails and memberDetails.
loginDetails (table_1 shown in the code)
loginID (PK) <-- auto increment
username
password
memberDetails (table_2 shown in the code)
memberID (PK) <-- auto increment
loginID (FK)
These are the codes I have so far, however the loginID in memberDetails table are always 0,:
PHP codes
$Query = "INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username']."',
'".$formValue['password']."')";
if (mysqli_query($Link, $Query)) {
$lastID = mysql_insert_id();
$Query2 = "INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')";
if (mysqli_query($Link, $Query2)) {
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true', 'action'=>'login','html'=>$message, 'console.log'=>$Query));
}
else {
$message = "Error occur in query2";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
}
else {
$message = "Error in query1";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
It would be great if this question can be solved, as i have been struggling in this for 3 nights already. Cheers.
You can place your queries in an array. Loop through the array. If an error occurs, exit the script.
$myQueries = array(`"INSERT INTO $table_1 VALUES (NULL,
'".$formValue['username'].",
'".$formValue['password']."')",
"INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')"
)`;
for($i = 0; $i < count($myQueries); $i++){
if (mysqli_query($Link, $myQueries[$i])) {
$lastID = mysql_insert_id();
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true',
'action'=>'login',
'html'=>$message,
'console.log'=>$Query));
}
else {
$message = "Error occur in query[$i]";
echo json_encode(array('action'=>'error',
'html'=>$message,
'console.log'=>$Query));
exit; // stops the next query
}
}
}
Here I have a code which inserts data into db. It's working fine now, but I want the title to have a minimum of 4 characters and the body a minimum of 500.
Here is my code:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if ($title && $body && $category) {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}else {
echo "data missing";
}
}
?>
I tried the code below to put minimum requirements for the title and body, but it echoes the title error message whenever you submit data even when the title contains more than 5 characters.
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title<5)) {
echo "Title must be of minimum 5 characters";
}
else {
if (strlen($body<500)) {
echo "Title must be of minimum 500 characters";
}
else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}
else {
echo "error";
}
}
}
}
?>
A question as such deserves an explanation for future readers to the question.
The reason why your code is failing, is that:
if (strlen($title<5))
evaluates to:
function($string conditional)
when the syntax is:
function($string) conditional
The manual states:
int strlen ( string $string )
http://php.net/manual/en/function.strlen.php
Example pulled from the manual:
if (strlen($foo) === 0) echo 'Null length is Zero <br>';
Plus, as stated in comments. Your query is subject to an SQL injection. It's best to use a prepared statement.
Consult the following links:
How can I prevent SQL injection in PHP?
https://en.wikipedia.org/wiki/Prepared_statement
I think the issue lies with the conditions you used.
if (strlen($title<5))
should be
if (strlen($title)<5)
similarly
if (strlen($body<500))
to be
if (strlen($body)<500)
Try this:
<?php
if(isset($_POST['submit'])) {
//get blog data
$title=strip_tags($_POST['title']);
$body=strip_tags($_POST['body']);
$posted_by = $first_name;
$category=$_POST['category'];
$bio = $bio;
$userid=$_COOKIE['user'];
$date = date ('d-M-Y');
if (strlen($title) < 5) {
echo "Title must be of minimum 5 characters";
}else {
if (strlen($body) <500 ) {
echo "Body must be of minimum 500 characters";
}else {
$query = "INSERT INTO blogs (userid, title, body, posted_by, bio, category_id, posted) VALUES ('$userid', '$title', '$body', '$posted_by','$bio', '$category', '$date')";
$run = mysqli_query($con,$query);
if($query) {
echo "posted";
}else {
echo "error";
}
}
}
}
?>