PHP, question about searching and updating a record - php

I have a question, I am new to PHP and I have been working on some exercises. The one I am currently working on is to create a simple form that will search a database (first name, last name). The returned results should then be populated into another form. This way, if I want to update the record, all I have to do is change the value of the populated form and hit Update. I have create the database no problem.
The following is the code. (Please don't laugh, I'm very new...I am sure there are much more efficient ways of doing this, but I'm just playing around right now)
Here is the form:
<form action="" method="post">
<strong>Search for name</strong><br>
<label for="fname">First Name</label>
<input type="text" name="fname">
<label for="lname">Last Name</label>
<input type="text" name="lname">
<input type="submit" name="submit" value="Search">
</form>
And here is the PHP:
if( isset( $_POST['submit'] ) ){
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
if ( $first_name == NULL || $last_name == NULL ) {
echo "please enter search record";
}
else {
$query = "SELECT first_name, last_name FROM formdata WHERE first_name LIKE '%$first_name%' OR last_name LIKE '%$last_name%'";
$result = mysqli_query( $conn, $query );
$result_array = mysqli_fetch_row( $result );
$fname_value = $result_array[0];
$lname_value = $result_array[1];
echo "
<form action='' method='post'>\n
<label for='fname_u'>First Name</label>\n
<input type='text' name='fname_u' value='$fname_value'>\n
<label for='lname_u'>Last Name</label>\n
<input type='text' name='lname_u' value='$lname_value'>\n
<input type='submit' name='update' value='Update'>\n
</form>";
}
}
if( isset( $_POST['update'] ) ) {
$first_name_u = ( $_POST['fname_u'] );
$last_name_u = ( $_POST['lname_u'] );
$query_update = "UPDATE formdata SET first_name = '$first_name_u', last_name = '$last_name_u' WHERE first_name = '$fname_value';";
echo $query_update; // this is just for testing
}
This code seems to work and do what I want, all the way up to when I submit the updated information. I can't figure out how to carry over the value of the $fname_value variable to the if( isset( $_POST['update'] ) ) conditional. I am thinking I can't because they are two different POSTS? I really don't know...I just need to find a way to get value of the retrieved form data and use for the WHERE clause.
Again, I'm very new and just getting my feet wet with this kind of stuff ... Any help would be great
Thanks

I think you have a typo in your code. Your POST data is saved to the variable $first_name, but when you query SQL you are using $first_name_r instead of $first_name.

I'm thinking the typo is the answer, but I have to point out one deadly mistake you've made, and that is that you're piping user-supplied input directly into an SQL query. This opens your code to a slew of malicious attacks called SQL injection attacks. I'm not trying to be preachy, but it's very important that you read and understand that article, especially the part about Mitigation at the bottom.
I would suggest you use something like this instead:
$query = 'SELECT first_name, last_name '.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = mysqli_prepare($dbh, $query);
mysqli_stmt_bind_param($sth, "s", '%'.$first_name.'%');
mysqli_stmt_bind_param($sth, "s", '%'.$last_name.'%');
$result = mysqli_execute($sth);
I know it's a bit longer and more complicated, but trust me, it will save you a world of headache. The sooner you learn about this and get it deeply ingrained in your psyche that you can never, ever, ever write a query that passes unsanitized input straight to the database, the happier we all will be (and the longer you will get to keep your job eventually. ;).
Sorry if I'm coming on strong, but in my opinion, the single most important lesson you need to pick up early in developing database-driven web sites is that you really need to be proficient at spotting injection vulnerabilities to the point where it's automatic and when you see it, you think, "Ooh! Noooo! Don't do that!!!"

Above answer found your isssue, but on a sidenote:
$first_name = $_POST['fname'];
$last_name = $_POST['lname'];
Do not do this. That my friend is the most common security vulnerability for php applications.
The most 2 most important things to remember when scripting is
Filter input, and
2: Escape output.
See this write-up for more details ..
In your case, the input values are not filtered, or checked for malicious/improper values.
Here is another primer on this page to see a few tips and how to address filtering.
Keep it up, those exercises are a fine way of picking up chops.
Happy coding friend.

Okay, re-reading your post, I think I see what you're trying to do and where you're having difficulty. Normally, you won't have two separate pages for one identical form like this. Typically, you'll code it more along these lines, and please keep in mind that I'm winging this off the top of my head, not actually testing it, so minor corrections and/or tweakage may be required:
<?php
$fname_value = '';
$lname_value = '';
if (isset($_POST['submit']) && $_POST['submit'] === 'Search') {
if (isset($_POST['fname']) && isset($_POST['lname'])) {
// We are processing a submitted form, not displaying a brand new one
// from scratch. Code any post-validation steps.
// Fetch the user information from the database. You'll need to define
// the $host, $user, $password, and $dbname variables above, or
// substitute literal strings with real information in here.
$dbh = new mysqli($host, $user, $password, $dbname);
$sql = 'SELECT first_name, last_name'.
'FROM formdata WHERE first_name LIKE ? OR last_name LIKE ?;';
$sth = $dbh->prepare($sql); // Use parameters to avoid injection!
$sth->bind_param('s', $_POST['fname']);
$sth->bind_param('s', $_POST['lname']);
if ($sth->execute()) {
$result = $sth->get_result();
if (($row = $result->fetch_assoc()) != NULL) {
// Set the default values displayed in the text edit fields.
$fname_value = $row['first_name'];
$lname_value = $row['last_name'];
}
}
// Whatever other processing you want to do if this is a submitted
// form instead of displaying the page from scratch.
}
}
?>
<html>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<strong>Search for name</strong><br />
<label for="fname">First Name</label>
<input type="text" name="fname" value="<?= htmlentities($fname_value) ?>">
<label for="lname">Last Name</label>
<input type="text" name="lname" value="<?= htmlentities($lname_value) ?>">
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>

Related

Re-populating / Editing HTML form inputs using MySQL Data

Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...

MYSQL - Update database creates new record each time

Each time i update the database, it create a new row with the new information i was trying to update and a new customerID each time, is there a way to resolve this.
The update query calls two tables Cus_acct_details and cus_register. The query is meant to change cus_email in both tables, and update all the information in cus_acct_details.
PHP
<?php
//$user = $_SESSION["Cus_Email"];
$Cust_ID = $_SESSION["CustomerID"];
if (isset($_POST['Update'])) {
$UpdateFname = $_POST['fname'];
$UpdateLname = $_POST['Lname'];
$UpdateEmail = $_POST['email'];
$UpdatePhone = $_POST['phone'];
}
$sql = $dbc->query("UPDATE Cus_Register, Cus_acc_details
SET Cus_acc_details.CUS_Fname = ' $UpdateFname',
Cus_acc_details.CUS_Lname = ' $UpdateLname',
Cus_acc_details.CUS_Email = ' $UpdateEmail',
Cus_acc_details.Cus_Phone = ' $UpdatePhone',
Cus_Register.CUS_Email = ' $UpdateEmail',
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
WHERE Cus_Register.CustomerID = '$Cust_ID'
");
print_r($_POST);
header('Location: Cus_Account.php');
?>
HTML
<section class="container">
<form id="myform " class="Form" method="post" action="Cus_Account.php?c_id=<?php echo $c_id ?>" accept-charset="utf-8">
<!-- <div id="first">-->
<input type="text" id="fname" name="fname" value="<?php echo $_SESSION['fname']; ?>" required>
<input type="text" id="lname" name="lname" value="<?php echo $_SESSION['lname']; ?>" required>
<input type="text" id="email" name="email" value="<?php echo $_SESSION['Cus_Email']; ?>" required>
<input type="number" id="phone" name="phone" value="<?php echo $_SESSION['phone']; ?>" required>
<input type="submit" name="Update" value="Update">
<br>
</form>
The $cust_id variable was defined earlier on.
Where have a gone wrong.
An UPDATE statement won't insert a new row. There must be an INSERT statement running. (1)
The syntax of the update statement looks wrong to me, I'd expect that to be throwing an error.
The ON clause is used with the JOIN keyword, but the old-school comma operator is used for the join operation. The SET clause should be the last thing before the WHERE clause.
UPDATE Cus_Register
JOIN Cus_acc_details
ON Cus_Register.Cus_Email = Cus_acc_details.Cus_Email
SET Cus_acc_details.CUS_Fname = ?
, Cus_acc_details.CUS_Lname = ?
, Cus_acc_details.CUS_Email = ?
, Cus_acc_details.Cus_Phone = ?
, Cus_Register.CUS_Email = ?
WHERE Cus_Register.CustomerID = ?
It seems odd that there's an extra space in the string literals.
Assigning the return from a ->query() to a variable is a common pattern. But naming that variable $sql is very strange.
The normative pattern is to assign the SQL text (a string) to a variable named $sql, and then referencing the variable
$sql = 'SELECT foo FROM bar ORDER BY foo LIMIT 1';
$result = $dbc->query($sql);
Then check the return from query, to see if it was successful, or if an error occurred. If you're using PDO, you can configure the connection to throw an exception, and handle it in a catch block.
If your code doesn't do that, it's putting it's pinky finger to the corner of its mouth Dr. Evil style and saying "I'm just going to assume it all goes to plan. What?"
Also, the code appears to be vulnerable to SQL Injection. If any potentially unsafe values are included in the SQL text, those values must be properly escaped before they are included.
The preferred pattern is not even include the values in the SQL text, but to use prepared statements with bind placeholders, and supply the values through the placeholders.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
(1.) Of course it's possible to define a BEFORE UPDATE and/or an AFTER UPDATE trigger that performs an INSERT. But it's the INSERT statement that inserts the row, even if the firing of the trigger is "caused" by running an UPDATE.
Set CustomerID to be a key and add an ON DUPLIACTE KEY UPDATE clause

php code not working as expected form will not submit the correct data

so I've got this code that supposedly sends you an email after you entered a valid one and answered a security question. My problem is the fact that the form won't submit the answer i've given it. It always echoes "submit" on the begging of the second php block. Also if u can spot any other errors i might have missed let me know please. Thanks anticipated.
<?php
define ('DB_SERVER','fenrir');
define ('DB_USERNAME','ArchivrTW');
define ('DB_PASSWORD','vPOZOa1txS');
define ('DB_DATABASE','ArchivrTW');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$connection)
{
die('Could not connect because: ' . mysql_error());
}
?>
<?php
$test = $_POST['email'];
$query = "SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test";
echo(strlen($query));
if(strlen($query) > 42)
{
$query1 = "SELECT 'SecurityQ' from 'USERS' WHERE 'EMAIL' =$test";
$query2 = "SELECT 'SecurityA' from 'USERS' WHERE 'EMAIL' =$test";
$result = mysqli_query($connection,$query);
$result1 = mysqli_query($connection,$query1);
$Results = mysqli_fetch_assoc($result);
$Results1 = mysqli_fetch_assoc($result1);
$Results2 = mysqli_fetch_assoc($result2);
echo($Results1);
}
?>
<form action="recover.php" method="post">
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
<p><input type="submit" name="answer" id="answer" /> </p>
</form>
<?php
$answer=$_POST['answer'];
echo($answer);
if (count($Results) >= 1 && strcmp($_POST['answer'],$Results2) == 0)
{
$REQ_STATUS = 1;
$new_passwd = rand(1,1000000);
$to = $email;
$subject = "Archivr-Forgot Password";
$msg = "Use this generated password to log in then change it using the Edit Profile Menu";
mail($to, $subject, $msg);
}
else
{
$message="Account not found or wrong security question answer";
}
if($REQ_STATUS == 1)
{
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
}
?>
</body>
</html>
The first block works, problem is the form or the second block.
You are vulnerable to sql injection attacks;
You have duplicate field names:
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
^^^^^^^^^^^^
<p><input type="submit" name="answer" id="answer" /> </p>
^^^^^^^^^^^^^
Since the field names are the same, the submit button overwrites/replaces the text field, and you end up submitting a blank value.
You're using the incorrect identifier qualifiers for all your tables and columns being single quotes and not wrapping the $test variable in quotes; it's a string.
This one for example:
SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test
should read as
SELECT `EMAIL` FROM `USERS` WHERE `EMAIL`='$test'
where you may have seen a tutorial somewhere, that the ticks resembled regular single quotes. They are not the same; those are two different animals altogether.
You will then need to follow the same method above and do the same for the rest of your queries.
Using this for example:
$result = mysqli_query($connection,$query) or die(mysqli_error($connection));
would have signaled a syntax error.
Then this mysql_error() - That should read as mysqli_error($connection). You cannot mix MySQL APIs. They do not intermix with each other.
You also don't seem to be doing anything with:
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
Whether it's relevant to the question or not, you're not actually executing that query.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
References:
https://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
http://php.net/manual/en/mysqli.error.php
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Plus, since you're using the entire code in one file, you will get warnings to the effect of "Undefined index xxx....", therefore you will need to use a conditional isset() and or !empty() around your executable code and for the POST arrays.
Passwords:
I'm hoping you're using a modern-day password hashing method, since this looks to me, being related to resetting passwords.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Both your form field and your submit button have a name of "answer". Rename your submit button name to "submit" or something else.

Processing, validating, and sanitizing data

Ok I have been stuck on this for some time now. I have a form. The form is in "index.php".
I send the form data to a php file called, "processuserform". I extract all the inputs and assigned them each to their own variable. I then took each variable and ran them through a function that I believe trims and strips the input from any unwanted characters. Within the same function I transformed any special characters into their HTML forms. Next I tried to validate the email. I used a PHP filter for this. I am uncertain on many things and have been searching for quite some time for an answer or at least a path to follow so I can learn how to properly sanitize and validate information. I am under the impression I will need to treat passwords different then everything else and will learn that after I learn how to validate and sanitize information. What you see below is what I have gathered from various sources on the net, which may end up being an incorrect way of designing a web page. I have achieved client side validation using Javascript but am fearful for my site because I do not have server side validation up. What happens if someone, who has javascript turned off, enters the wrong kind of information? How do they get sent back to the registration part and told they have made a mistake. I dont want people being led to a blank screen when they incorrectly enter information. I just want my site to be validated on the server side. I have literally been trying to learn this for 3 months. It is not that I am unintelligent but cannot find a set way to go about doing this. With so many ways I am confused ast to the path to take and what to do next. I will leave my code below and hopefully you guys will have compassion and patience for me. Thanks in advance.
==========================================================================
Form
==========================================================================
<form method="POST" name="signup" action="php/processuserform.php">
<input id="firstname" onkeyup="validateFirstName()" placeholder="First Name"
type="text" /><label id="firstnameprompt"></label>
<br><br>
<input id="lastname" onkeyup="validateLastName()" placeholder="Last Name"
type="text"/>
<label id="lastnameprompt"></label>
<br><br>
<input id="Email" onkeyup="validateEmail()" placeholder="Email" type="text" /><label
id="Emailprompt"></label>
<br /><br />
<input id="Password" onkeyup="validatePassword()" placeholder="Create Password"
type="password" /><label id="Passwordprompt"></label>
<br /><br />
<strong>Male</strong><input id="Gender" type="radio" name="sex" value="male">
<strong>Female</strong><input id="Gender" type="radio" name="sex" value="female">
<br /><br />
Click "Submit" if you agree to "Terms And Conditions"
<br>
<input id="submit" onclick="return validateUserRegistration()" value="Submit"
type="submit" name="submit"/><label id="submitprompt"></label>
<br /><br />
<hr>
</form>
====================================================================
//How I am Processing it.
====================================================================
<?php
//====================================
//Variables
$first_name= check_input($_POST['firstname']);
$last_name= check_input($_POST['lastname']);
$email= check_input($_POST['Email']);
$password= check_input($_POST['Password']);
$gender= check_input($_POST['Gender');
//====================================
//Trim and strip first name
function check_input($first_name)
{
$first_name = trim($first_name);
$first_name = stripslashes($first_name);
$first_name = htmlspecialchars($first_name);
return $first_name; };
//====================================
//Trim and strip last name
function check_input($last_name)
{
$last_name = trim($last_name);
$last_name = stripslashes($last_name);
$last_name = htmlspecialchars($last_name);
return $last_name; };
//====================================
//Trim and strip email
function check_input($email)
{
$email = trim($email);
$email = stripslashes($email);
$email = htmlspecialchars($email);
return $email; };
//=====================================
//Trim and Strip Password
function check_input($password)
{
$password = trim($password);
$password = stripslashes($password);
$password = htmlspecialchars($password);
return $password; };
//======================================
//Trim and strip Gender
function check_input($gender)
{
$gender = trim($gender);
$gender = stripslashes($gender);
$gender = htmlspecialchars($gender);
return $gender; };
//=========================================================
//Validate Email
$email
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
echo 'This should be a valid email';
}
else
{
echo 'You need some guidance':
}
//========================================================
$hostname="this is right";
$username="this is right";
$password="this is right";
$dbname="this is right";
$db_conx = mysqli_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
if(mysqli_connect_errno()){
echo mysqli_connect_error();
exit();
}
$select = mysqli_select_db($db_conx,$dbname);
mysqli_query($db_conx,"INSERT INTO users (firstname, lastname, email, password,
gender)
VALUES ('$first_name', '$last_name', '$email', '$password', '$gender')");
mysqli_close($db_conx);
header("Location: pages/profile.php")
?>
Well after you removed the unwanted characters from all of your user inputted variables, you now have to validate them as well!
From what I have learned in the past, one of the assumptions you should have as a developer is to NEVER trust that all users know the correct inputs for forms! Never trust the user! So with that in mind, we go and validate server side.
Validation in simplest terms is just making sure that the user inputs data that will work (I don't know the right way to put it) in a way to maintain the quality of your application.
Let's take one of your variables for example.
$email
Okay, you did a validation to check if it's an email, but there are better ways to validate it and you also need to check for other factors such as if the user inputs a blank space etc.
function validateEmail($email)
{
//Regex is a great way to validate email. This checks if it has one # sign and also the lengths of the email.
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email))
{
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
//check if the input was something other than a whitespace.
//Even if you put inside the textfield "required" in html, a whitespace will still be a //valid input so you better check to make sure that users aren't allowed to enter empty //fields!
if (!preg_match("/^[a-zA-Z ]*$/",$email))
{
return false;
}
return true;
}
This is just an example of how you can validate email using Regular Expressions.
You can even validate whether or not the domain is a real domain, or you can validate if the email contains any profane words and such. The key is to know what you don't WANT going into your system.
Make sure you also sanitize your queries in order to avoid any attacks.
Hope this sort of helps!
Cheers!

Making the transition from mysql_ to MySQLi or PDO

I have been searching here and Google for how to change all my MYSQL scripts to MYSQLI or PDO starting just from the beginning. The thing is that for some reason I cannot understand because I am inexperienced and I cannot make a simple session work. Here is what I will start doing because I want to learn the new MYSQLi:
I picked the registration form ( I will not use it in public, my site is just for friends and no more people I choose who will be member and I sign em up )
<?php
/* instantiate our class, and select our database automatically */
$sql = mysqli('localhost','user','password','database');
/*
let's assume we've just received a form submission.
so we'll receive the information, and we'll escape it
this step is not necessary, but why not.
*/
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
/* build the query, we'll use an insert this time */
$query = $sql->prepare("INSERT INTO `tablename` VALUES ('?','?','?');");
/*
bind your parameters to your query
in our case, string integer string
*/
$query->bind_param("sis",$name,$age,$email);
/* execute the query, nice and simple */
$query->execute();
?>
This is ok for me easy to understand, now I cannot find a good example of user login, all examples I find are from expert developers and they mostly create so complex scripts that I dont even need it. Already installed many examples ready made and it feels like they are not really good.
What I have been waiting and looking for and searching 1 WEEK 12 hours a day is:
I want the user to simply login and then the script will have something simple like this:
PAGE START
HELLO <PHP ECHO USERNAME> <PHP ECHO AGE> <PHP ECHO ANYTHING FROM DB>
THANKS
<?php
ELSE
IF USER IS NOT LOGGED IN
REDIRECT TO THE PAGE NOTMEMBER.PHP
?>
PAGE END
Why? Because that's the easy and simple way I use to code in MYSQL and all the sites structure is based like this.
Examples or demo sites would also be helpful.
Thanks a lot
I will recommend you to learn PDO(PHP Data Objects) instead of MySQLi cause PDO supports 12 different database drivers while MySQLi only support MySQL Database.
To know the difference between PDO and MySQLi visit-PDO vs. MySQLi: Which Should You Use?
To learn about PDO visit this very nice tutorials-
1.Why you Should be using PHP's PDO for Database Access
2.PHP Database Access: Are You Doing It Correctly?
Your table needs to have a password column as well.
HTML log in form:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="email" />
<input type="text" name="password" />
<input type="submit" name="submit" value="Log in" />
</form>
Catch it in the PHP file:
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$pass = $_POST['password'];
if($email != '' && $pass != '') { //both not empty, proceed
$checkUser = $sql->prepare("SELECT * FROM `users` WHERE `email` = ? AND `pass` = ?");
$checkUser->bind_param('ss', $email, $pass);
$checkUser->execute();
if($checkUser->num_rows() > 0) { //if user exists with given email and pass
$_SESSION['logged-in'] = 1;
}
}
}
Make sure you put session_start(); at the top of each PHP file. Then you simply use
if($_SESSION['logged-in'] == 1) {
echo 'this is for logged in users';
} else {
header("Location: notMember.php");
exit();
}

Categories