I have a registration php file which is linked with a database I created in a user I created in phpmyadmin. But the issue is whenever I submit values into it the database is not being updated. I don't know what is the issue also I am beginner in this area so I m not fully aware of the functionalities. Links to some images are below. Just go through them you will get a better idea of my query
https://drive.google.com/file/d/1ZtiRxPpTT3NNCut345TSjXOAkIsVsZkK/view?usp=drivesdk
https://drive.google.com/file/d/1FZOEBq641DpmNWXeC3_LYy_FTK49Hm87/view?usp=drivesdk
https://drive.google.com/file/d/1PHbKSPVTnJvvJ-1vWVQwga61JDlpxBIK/view?usp=drivesdk
Try with the below code. Also, you are showing the success message even though you don't know if the query was executed with success.
if(isset($_POST['submit1']))
{
$number = $_POST['number'];
$name = $_POST['name'];
if(empty($number))
{
$errornumber = "Number empty !";
}
elseif(empty($name))
{
$errorname = "Name empty !";
}
else {
$query = "INSERT INTO `student` (`number`,`name`) VALUES('$number','$name')";
if (mysqli_query($link, $query)) {
$success = '<div class="alert alert-success col-lg-6 col-lg-push-3">
Registration successfully. You will receive an email when your account is approved.
</div>'
}
}
}
Now, all you have to do is use , and where you want them to show.
if this doesn't work, it means you have other issues, posting images with portions of code is never a good option to go about asking for help. Nobody will steal your code.
Related
Can someone help me check why my query keeps returning the user exists despite me entering a whole set of new data? The code should be correct? I have been testing this code for awhile and I can't see where its gone wrong.
The request is sent from the app and then it takes the data via post. However something is preventing me from inserting a new row.
$checkuserexistsquery = "SELECT email, phone FROM users WHERE email='$email' OR phone='$phone'";
$insertuserquery = "INSERT INTO users (firstname,lastname,dateofbirth,phone,email,password) VALUES ('$firstname','$lastname','$dateofbirth','$phone','$email','$password')";
$checkuserexistsresults = mysqli_query($conn,$checkuserexistsquery);
if($checkuserexistsresults===FALSE){
echo "Check user query failed";
}else{
$countcheckuserexistsresults = mysqli_num_rows($checkuserexistsresults);
if($countcheckuserexistsresults>0){
//user already exists
echo "User already exists";
}else{
//user doesn't exist
$insertuserresults = mysqli_query($conn,$insertuserquery);
if($insertuserresults===FALSE){
echo "Insert user query failed";
}else{
echo "Insert successful";
}
}
}
mysqli_close($conn);
From the comments, i think you should confirm if $email and $phone should be the correct one that you want. You can echo or var_dump them before concat it to $checkuserexistsquery. I presume that maybe you assign the values, email: test#test.com or phone: 12345 somewhere else in your code, because i don't see any logical error from your code.
Hello I cannot get my php to post to mysql. I get no errors when submitting, but entries are not showing up in my database. I appreciate anyone that can give me advice on how I can fix this. I tried to search around here but couldnt find a dirrect reason on why my php code is not working.
<?php
if (isset($_POST['submit'])) {
if (empty($_POST['element_1']) || empty($_POST['element_2'])) {
die("You have forgotten to fill in one of the required fields! Please make sure you submit your name, and paypal e-mail address");
}
$entry = htmlspecialchars(strip_tags($_POST['entry']));
$timestamp = htmlspecialchars(strip_tags($_POST['timestamp']));
$name = htmlspecialchars(strip_tags($_POST['element_2']));
$email = htmlspecialchars(strip_tags($_POST['element_1']));
$comment = htmlspecialchars(strip_tags($_POST['element_3']));
$comment = nl2br($comment);
if (!get_magic_quotes_gpc()) {
$name = addslashes($name);
$url = addslashes($url);
$comment = addslashes($comment);
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("The e-mail address you submitted does not appear to be valid. Please go back and correct it.");
}
mysql_connect('host', 'username', 'password') ;
mysql_select_db('database name');
$result = mysql_query("INSERT INTO payments (entry, timestamp, name, email, comment) VALUES ('$entry','$timestamp','$name','$email','$comment')");
header("Location: post.php?id=" . $entry);
}
else {
die("Error: you cannot access this page directly.");
}
?>
Thanks in advanced for your time, understanding, and knowledge. I greatly appreciate it.
advice on how I can fix this
use var_dump($_POST); after if(isset($_POST['submit']))
do $sql="" and var_dump($sql) and mysql_query($sql);
after query var_dump(mysql_insert_id());
and var_dump(mysql_error());
and dont forget: error_reporting(E_ALL); at the top of the file
Then look what happens
[optional] after first query use SHOW COUNT(*) WARNINGS
Things you should check:
I cant see your database design, so you'll have to make sure that your database columns and table match correctly with what is specified in your database.
echo your variables to make sure none are empty.
Ensure that you are not inserting a string in column of type int or vice versa.
Make sure your form method is POST and that your name attributes match what you have specified in your variables ie $_POST['name_attr'].
The order of your insert columns should be the same order as in your table.
Lastly, i hope host,username,password and database name are just placeholders for your real database info? if not, that's the problem.
I'm trying to make two visually similar web environments. One is supposed to be secure and the other one isn't. I figure doing things right AND wrong and having examples will help me while I'm still learning. Right now I'm doing the log in forms but while the more secure code works right, the insecure code is literally accepting everything, even blank inputs! I can't tell what the difference is that is making this happen.
This is from the more secure log in page.
// The user is logging in
} else if (isset($_POST['logsubmit'])) {
// collects value from login form
$loguser = safe_input($_POST['loguser']);
$logpass = md5($_POST['logpass']);
//This section needs encryption
$logcheck1 = mysqli_query($con,"SELECT * FROM users WHERE username ='$loguser'");
$logcheck2 = mysqli_num_rows($logcheck1);
if ($logcheck2 == 0) {
echo ('There is no record of that username being currently active');
goto logform;
}
while ($logcheck3 = mysqli_fetch_array($logcheck1)) {
if ($logpass != $logcheck3['password']) {
echo ('Incorrect password used.');
goto logform;
}
}
display:
$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$loguser'");
while ($data = mysqli_fetch_array($user)) {
if ($data['profile_pic'] != NULL) {
$pic = $data['profile_pic'];
} else {
$pic = "img/blank_profile.png";
}
}
setcookie('testsiteUser',$loguser,time()+3600);
setcookie('testsitePass',$logpass,time()+3600);
echo ('<h2 id="greenborder">Hello, <a id="purpleborder"
href="userpage.php">'.$loguser.'</a>!</h2>
<img class="profile_bar" src="'.$pic.'">');
?>
<p>
<form action="<?php echo ($_SERVER['PHP_SELF'])?>" method="POST">
<input type="submit" name="logout" value="Log Out">
</form></p>
<?php
} else {
logform:
And then after the logform: marker is the log in form. There is more code above comment about the user logging in. Let me know if anyone wants to see it. I don't know if it's relevant.
This works! If I log into this with the wrong user name or password, it'll say so. If I log in right, it'll say so.
This is the code from the more insecure version.
// The user is logging in
} else if (isset($_POST['logsubmit'])) {
// collects value from login form
$loguser = /*safe_input*/($_POST['loguser']);
$logpass = md5($_POST['logpass']);
/*
//This section needs encryption
$logcheck1 = mysqli_query($con,"SELECT * FROM users WHERE username ='$loguser'");
$logcheck2 = mysqli_num_rows($logcheck1);
if ($logcheck2 == 0) {
echo ('There is no record of that username being currently active');
goto logform;
}
while ($logcheck3 = mysqli_fetch_array($logcheck1)) {
if ($logpass != $logcheck3['password']) {
echo ('Incorrect password used.');
goto logform;
}
}
*/
$logcheck = mysqli_query($con,"SELECT * FROM users WHERE username = '$loguser' AND password = '$logpass'");
mysqli_free_result($logcheck);
if ($logcheck == 0){
echo ('Incorrect username or password');
goto logform;
}
//display:
/*$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$loguser'");*/
/*$userpic = $_SESSION["loguser"];
$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$userpic'");
while ($data = mysqli_fetch_array($user)) {
if ($data['profile_pic'] != NULL) {
$pic = $data['profile_pic'];
} else {
$pic = "img/blank_profile.png";
}
}*/
$_SESSION["loguser"] = $loguser;
echo ('<h2 id="greenborder">Hello, <a id="purpleborder" href="userpage.php">'.$_SESSION["loguser"].'</a>!<h2><p><img class="profile_bar" src="'.$pic.'">');
?>
<p>
<form action="<?php echo ($_SERVER['PHP_SELF'])?>" method="POST">
<input type="submit" name="logout" value="Log Out">
</form></p>
<?php
} else {
logform:
A lot of this is commented out because I started by copying this from the safer code which was made first. This logs in no matter what, and whatever I put into the user name input is displayed as the account name. I don't even know if the database is being queried.
I THINK that the 2nd version is somehow passing the goto login, but I can't see why it would work in the first version but not the second version. Or if I'm missing something else completely! I'm comparing both of these side by side, trying to make sure all the brackets have mates, but I'm still learning PHP. I know goto is awful and putrid and nobody likes it, but I feel like I'm using just how it's displayed in the online PHP manual where it comes out of an if, while, and for statement.
http://php.net/manual/en/control-structures.goto.php#example-162
I'm still building both of these so I realize there may be some big flaws in the first version that aren't present in the second version. I'm really just hung up on this one thing for now. Can anyone see whatever it is I'm missing here?
Sorry if the question is too long or I committed some other faux pas. This is my first question.
Your issue is because your second "less secure" option isn't checking the number of rows.
In your second script, you have:
$logcheck = mysqli_query(....
and then you try to check it
if($logcheck == 0) {..
That's completely wrong, it'll only ever return a mysqli resource or false. Also that mysqli_free_result(); might be causing issues (as stated in the comments by onegun). Comment it out and see what happens.
Another Note
You should be careful when using goto, especially if an error were to occur, you wouldn't be able to trace it to its origin and it's actually bad coding practice to rely on it.
Problem has been solved
I have created a form that processes the changing of user information from the admin side e.g. the admin changes a user's username and/or email. I am having trouble processing multiple queries.
For example, if the admin changes the username, the query works. If the admin changes the email address, the query works. But if the admin changes the username and email at the same time through the form then only the username changes.
Any ideas? I will submit my code but I will change variables for security reasons etc. Also, anything in capitals has been changed for security reasons. The code is all correct for each individual function because as I said, if I ONLY change the email, it works and actually changes. But if I change the username AND email, only the username will change despite the fact the email query runs and it echo's the email has been changed!
Also, it is worth noting that all of the fields e.g. username field and email field are part of one form that submits to one page.
if (isset($_POST['SUBMIT_BUTTON_PRESSED'])) {
//Gather all inputs from the form and sanitise it.
//REMOVED FOR SECURITY REASONS.
if($USERNAME_NEW != "") {
if($USERNAME_NEW == $CURRENT_USERNAME) {
echo "You have entered the username you are already using. Please enter a different username.";
} else {
$CHECK_USERNAME = "SELECT USERNAME_ROW FROM USERS_TABLE WHERE username='$USERNAME_NEW'";
$RUN_QUERY = mysqli_query($CONNECTION INFO, $CHECK_USERNAME);
$RESULT = mysqli_num_rows($RUN_QUERY);
if($RESULT > 0) {
echo "That username already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_username = true;
$USERNAME = $NEW_USERNAME; //NOT NEEDED BUT IT STILL WORKS
$THE_SQL_QUERY = "UPDATE USER_TABLE SET username='$USERNAME' WHERE username='$ORIGINAL USERNAME'";
$RUN_THIS_QUERY= mysqli_query($CONNECTION INFO, $THE_SQL_QUERY);
echo "The user's username has been changed to: ". $USERNAME;
}
}
}
if($EMAIL != "") {
if($EMAIL == $CURRENT_EMAIL) {
echo "You have entered the same email address to the one you are already using. Please enter a different email address.";
} else {
$CHECK_EMAIL = "SELECT USERS_EMAIL FROM USER_TABLE WHERE username='$USER'";
$CHECK_EMAIL_QUERY = mysqli_query($CONNECTION_INFO, $CHECK_EMAIL);
$RESULT = mysqli_num_rows($CHECK_EMAIL_QUERY);
if($RESULT > 0) {
echo "That email already exists. You cannot use that username again. Please enter another username.";
} else {
$editing_email = true;
$THE_NEW_EMAIL = $FINAL_EMAIL_THING; // AGAIN NOT NEEDED BUT STILL WORKS
$THE_SQL= "UPDATE USER_TABLE SET USER_EMAIL='$EMAIL' WHERE username='$USER' LIMIT 1"; // REMOVED THE LIMIT 1, STILL DOESN'T WORK
$RUN_THIS_QUERY = mysqli_query($CONNECTION, $THE_SQL);
if($RUN_THIS_QUERY) {
echo "The user's email has been changed."; // EVEN WHEN BOTH FIELDS ARE SUBMITTED THIS WORKS SO THE QUERY IS RUNNING BUT THE EMAIL DOESN'T CHANGE
}
}
}
}
Thanks for the help! Also, no un-witty remarks about how my question is structured etc. because I don't care to be honest. I just want this code working to be honest because I've been working on it for a while. This may be something simple or I might be using the wrong approach for this type of form submission.
Remember: THIS CODE DOES WORK WHEN I SUBMIT EACH FIELD SEPARATELY!
Its very hard to figure out as you are not producing the real code.
I think you have missed something here.
As you are using USER_NAME as key in the SQL's, make sure that you are using the updated username in the second sets of SQL (to update the email) as they are already replaced by the first SQL.
And there is no security risk while showing your codes snippets to someone else. Hide only the username/passwords or Identities. :)
I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php