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

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

Related

Some values do not submit: two different SQL's

In my last question people said that I need to use prepared statements to avoid SQL injection.
I'm changing the previous SQL's now to prepared statements, as y'all wanted.
The thing is, it submits the settings, this part:
$stmt_setsettings = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_setsettings, $usersettings_sql)) {
array_push($errors, "Safe SQL failed, could not insert settings. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_setsettings, "sssss", $email_show, $fname_show, $lname_show, $private_account, $profile_style);
mysqli_stmt_execute($stmt_setsettings);
}
But it submits none of the actual info I need (like the username, firstname, ...)
Also, at the end of the code below it should redirect to the new profile, normally if this feels it should display "Something went wrong, refer to the helpcenter. (SE100)" but it like refreshes the sign up page and throws no error, while there is an error: the not submitting info!
I tried searching up similar questions or fixes but nothing useful found.
Can you check out the following code and let me know what is the deal with the not submitting values? Thanks!
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1); // Encrypt the password before saving in the database
$user_ip = $_SERVER['REMOTE_ADDR']; // Getting the IP of the user
$bio = $config['default-bio']; // Setting default biography
$profileimg = $config['default-profileimg']; // Setting default profile image
$timestamp = date('d.m.Y'); // Defining the current date
$activity = "on"; // Defining which state the user profile is in, online
$userdata_sql = "INSERT INTO users (username, bio, activity, profileimg, regdate, email, password, firstname, lastname, gender, birthday, country, ip)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$usersettings_sql = "INSERT INTO usersettings (show_email, show_fname, show_lname, private_acc, profile_style)
VALUES (?, ?, ?, ?, ?)";
$stmt_signup = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_signup, $userdata_sql)) {
array_push($errors, "Safe SQL failed, could not sign up. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_signup, "sssssssssssss", $username, $bio, $activity, $profileimg, $regdate, $email, $password, $fname, $lname, $sex, $bday, $country, $user_ip);
mysqli_stmt_execute($stmt_signup);
}
$stmt_setsettings = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_setsettings, $usersettings_sql)) {
array_push($errors, "Safe SQL failed, could not insert settings. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_setsettings, "sssss", $email_show, $fname_show, $lname_show, $private_account, $profile_style);
mysqli_stmt_execute($stmt_setsettings);
}
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
// Generate user id
$generateid_sql = "SELECT id FROM users WHERE username=? ORDER BY id";
$stmt_generateid = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt_generateid, $generateid_sql)) {
array_push($errors, "Safe SQL failed, could not generate a new ID. Contact the helpdesk.");
} else {
mysqli_stmt_bind_param($stmt_generateid, "s", $username);
mysqli_stmt_execute($stmt_generateid);
$generateid_result = mysqli_stmt_get_result($stmt_generateid);
}
while ($id = mysqli_fetch_assoc($generateid_result)) {
if ($id['username'] <= 0) { // Checking if the user id is a valid id (not below or equal to 0), and if not, displaying a critical error
array_push($errors, "Something went wrong whilst signing up, please refer to the helpcenter. (SE100)");
}
if ($id['username'] > 0) { // Redirecting the user to his or her profile if it is a valid id
header('location: /content/users/profile?id=' . $id['username'] . '');
}
}
}
}
First off, PLEASE don't ever store passwords like this:
$password = md5($password_1); // <-- Totally insecure
Instead use the built-in password_hash() and password_verify() functions. See https://www.php.net/manual/en/faq.passwords.php for a good overview of why md5() is not secure and examples how to handle password storage correctly.
Also, I'd recommend pulling the user out of the database and validating the password, BEFORE setting $_SESSION['loggedin'] = true.
Regarding your question, I'd recommend adding some additional error handling and result checking around your calls to $conn->prepare() and $stmt->bind_param. See mysqli_stmt_execute() does not execute the prepared query for examples of how to check $stmt->errors.
Another general recommendation is checking $stmt->affected_rows to see if your insert statements are actually being executed as you expect. Your inserts should each be affecting 1 row.
Lastly, turning on the MySQL query log can be a great troubleshooting tool: How to show the last queries executed on MySQL? . Are all the SQL queries in your code showing up in the log? Try running the queries manually and see if the results look right.
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1); // Encrypt the password before saving in the database
$user_ip = $_SERVER['REMOTE_ADDR']; // Getting the IP of the user
$bio = $config['default-bio']; // Setting default biography
$profileimg = $config['default-profileimg']; // Setting default profile image
$timestamp = date('d.m.Y'); // Defining the current date
$activity = "on"; // Defening wich state the user profile is in, online
$userdata_sql = "INSERT INTO users (`username`, `bio`, `activity`, `profileimg`, `regdate`, `email`, `password`, `firstname`, `lastname`, `gender`, `birthday`, `country`, `ip`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$usersettings_sql = "INSERT INTO usersettings (`show_email`, `show_fname`, `show_lname`, `private_acc`, `profile_style`)
VALUES (?, ?, ?, ?, ?)";
$stmt_signup = $conn->prepare($userdata_sql);
$stmt_signup->bind_param("sssssssssssss", $username, $bio, $activity, $profileimg, $timestamp, $email, $password, $fname, $lname, $sex, $bday, $country, $user_ip);
if(!$stmt_signup->execute()){
array_push($errors,mysqli_error($conn));
}
$stmt_setsettings=$conn->prepare($usersettings_sql);
$stmt_setsettings->bind_param("sssss", $email_show, $fname_show, $lname_show, $private_account, $profile_style);
if(!$stmt_setsettings->execute()){
array_push($errors,mysqli_error($conn));
}
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
// Generate user id
$generateid_sql = "SELECT `id`,`username` FROM `users` WHERE `username`=? ORDER BY `id` limit 1";
$stmt_generateid=$conn->prepare($generateid_sql);
$stmt->generateid->bind_param("s", $username);
if(!$stmt_generateid->execute()){
array_push($errors,mysqli_error($conn));
}else{
$generateid_result = $stmt_generateid->get_result();
}
$username_assoc = mysqli_fetch_assoc($generateid_result);
if ($username_assoc['id'] > 0) {
// Redirecting the user to his or her profile if it is a valid id
header('location: /content/users/profile?id=' . $username_assoc['username'] . '');
}else{
array_push($errors, "Something went wrong whilst signing up, please refer to the helpcenter. (SE100)");
}
}

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

Check if textbox has a value

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...
}

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.

Categories