Check if textbox has a value - php

I am using a form to insert data to my database. I have a textbox with the ID and NAME name1.
If the user clicks on submit the PHP script sends the data to my database. But the insert statement is also executed when the textbox is empty. If there is no data entered the script creates an empty row in the database.
In my PHP script I want to check if the (value) in the textbox is empty or not.
I have tried multiple codes but the script still sends the empty data to my database.
Does someone know how I can check if there is data entered in the textbox.
Here is my script:
$query1 = "INSERT INTO product(user_id, name, price, tax) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query1);
$exec1 = $stmt->execute(array($_SESSION['USER_ID'], $name1, $price1, $tax1));
if($exec1){
echo '<p>product1 is created</p>';
} else {
echo '<p>error</p>';
}

It looks like that you are not checking if the text field is empty. Please try this:
if(!empty($_POST['name1'])) {
$query1 = "INSERT INTO product(user_id, name, price, tax) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query1);
$exec1 = $stmt->execute(array($_SESSION['USER_ID'], $name1, $price1, $tax1));
if($exec1){
echo '<p>product1 is created</p>';
} else {
echo '<p>error</p>';
}
}

check if a field is empty in order to return an error or a message just do this (brief example):
if (!(empty($_POST['textbox']))){
execute some code....
}
else {
execute some code...
}

Related

Query executed, but data not saved into database PHP/SQL

I'm trying to execute a SQL query that saves POST data into the database. The data comes in correctly, and the arrays that are coming with the POST data are converted to strings.
When the query gets executed the message 'Succesfully saved into database' appears, however the data isn't visible in the database, so there must be a little mistake inside my code, however I can't seem to find it.
See my code below:
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
mysqli_stmt_execute($stmt);
echo '<p>Succesfully saved into database</p>';
exit();
}
}
This is how the database looks like
Thanks in advance!
You should not assume that the query ran successfully because an exception was not thrown. You need to consider what the function returns and how many rows are affected before knowing if it ran successfully or not. Update your code to this and figure out what is going on:
Also check to make sure you are not just updating the same row over and over.
//database connection file
require "includes/dbh.inc.php";
foreach ($_POST as $post_var){
$obj = json_decode($post_var);
//Convert arrays to string
$userLikes = implode("|", $obj->userLikes);
$userEvents = implode("|", $obj->userEvents);
$userPosts = implode("|", $obj->userPosts);
$sql = "INSERT INTO visitor_data (id, fb_id, name, location, likes, events, posts) VALUES (NULL, ?, ?, ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: dom.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ssssss", $obj->userId, $obj->userName, $obj->userLocation, $userLikes, $userEvents, $userPosts);
if ( mysqli_stmt_execute($stmt) ) {
echo '<p>Succesfully saved into database</p>';
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt) );
}
}
mysqli_stmt_close($stmt);
}

Prevent Duplicate Entries in PHP MySQL

I have the following in my PHP.
$stmt = $conn->prepare("INSERT IGNORE INTO savesearch (user, searchedFor, sortOrder, buildURLString, aspectFilters, oneSignalId, totalEntries)
VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $user, $searchedFor, $sortOrder, $buildURLString, $aspectFilters, $oneSignalId, $totalEntries);
// set parameters and execute
$user = $_POST['user'];
$searchedFor = $_POST["searchedFor"];
$sortOrder = $_POST["sortOrder"];
$buildURLString = $_POST["buildURLString"];
$aspectFilters = $_POST["aspectFilters"];
$oneSignalId = $_POST["oneSignalId"];
$totalEntries = $_POST["totalEntries"];
if ($stmt->execute()) {
$output->success = true;
echo json_encode($output);
} else {
$error->error = mysqli_error($conn);
echo json_encode($error);
}
However, IGNORE is not being picked up, it continues to add entries. Is there another good way to fix this?
Id like to see if the USER and the URL is the same, dont add, echo duplicate entry.
IGNORE is actually mostly for the opposite of what you want here. Instead, you can amend your MySQL table something like:
ALTER TABLE savesearch ADD UNIQUE KEY(user, buildURLString)
Then remove your IGNORE keyword

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)

Inserting Multiple values into MySQL database using PHP

I'm wondering how to insert multiple values into a database.
Below is my idea, however nothing is being added to the database.
I return the variables above (email, serial, title) successfully. And i also connect to the database successfully.
The values just don't add to the database.
I get the values from an iOS device and send _POST them.
$email = $_POST['email'];
$serial = $_POST['serial'];
$title = $_POST['title'];
After i get the values by using the above code. I use echo to ensure they have values.
Now I try to add them to the database:
//Query Check
$assessorEmail = mysqli_query($connection, "SELECT ace_id,email_address FROM assessorID WHERE email_address = '$email'");
if (mysqli_num_rows($assessorEmail) == 0) {
echo " Its go time add it to the databse.";
//It is unqiue so add it to the database
mysqli_query($connection,"INSERT INTO assessorID (email_address, serial_code, title)
VALUES ('$email','$serial','$title')");
} else {
die(UnregisteredAssessor . ". Already Exists");
}
Any ideas ?
Since you're using mysqli, I'd instead do a prepared statement
if($stmt = mysqli_prepare($connection, "INSERT INTO assessorID (email_adress, serial_code, title) VALUES (?, ?, ?)"))
{
mysqli_stmt_bind_param($stmt, "sss", $email, $serial, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is of course using procedural style as you did above. This will ensure it's a safe entry you're making as well.

If(!empty($_POST)) TRUE all the time?

Despite hours of debugging, searching and reading, I can't figure out why the code below isn't working!? For debugging I have placed echo '1';, echo '2'; and echo '3'; in the code and I only get 1 on the screen when I run the code. And the most strange thing is that I get 1, both if the fields in the form are empty or not!?
I have followed a video tutorial from PHP Academy on Youtube, and I'm pretty sure I have written exactly the same code as in the video.
Youtube
Preciate some help to be able to continue!
EDIT 1: Have changed bio_name to bio
EDIT 2: Have changed firts_name to first_name
EDIT 3: Added created in SQL query
if(!empty($_POST)){
if(isset($_POST['first_name'], $_POST['last_name'], $_POST['bio'])){
echo '1';
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$bio = trim($_POST['bio']);
if(!empty($first_name) && !empty($last_name) && !empty($bio)){
echo '2';
$insert = $db->prepare("INSERT INTO people (firts_name, last_name, bio, created) VALUES (?, ?, ?, NOW())");
$insert->bind_param('sss', $first_name, $last_name, $bio);
if($insert->execute()){
header('Location: index.php');
echo '3';
die();
}
}
}
}
You're checking $_POST['bio'] in the first conditional and assigning $_POST['bio_name'] to $bio, which is probably empty and fails the second conditional.
Also, your insert query seems wrong - you are listing 3 fields and 4 values to insert. It should have the same number of listed fields and values:
INSERT INTO
people (first_name, last_name, bio, <LACKING FIELD>)
VALUES ( ?, ?, ?, NOW() )

Categories