PHP Validation with SQL - php

Hi I'm brand new to PHP and I'm just doing a simple form to learn. It just contains an email address, I want to Validate the information and send it to the database. My problem is connecting it to a database. I've done a few tutorials but just leave myself confused.
Right now this is my homepage
reg.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Registration Form</title>
</head>
<body>
<?php include("validation.php"); ?>
<form method="post" action="connect.php" name="form">
<ul id="errors">
<li><?php echo $err_email; ?></li>
</ul>
<div id="wrapper">
<div>Email</div>
<div class="input"><input type="text" name="email" value="<?php echo $val_email; ?>" /></div>
</div>
</form>
</body>
</html>
This is my validation.php file
<?php
if($_POST)
{
$email = $_POST['email'];
// Email
if (preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $email)) {
$val_email = $email;
}else{
$err_email = 'Please enter valid Email address.';
}
if((strlen($val_email)>0) ){
header("Location: reg");
}else{ }
}
?>
finally my connect file
<?php
$host="localhost";
$username="admin";
$password=""; // Mysql password
$db_name="davidtest"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("davidtest")or die("cannot select DB");
// Get values from form
$email=$_POST['email'];
// Insert data into mysql
$sql="INSERT INTO $users(email)VALUES('$email')";
$result=mysql_query($sql);
// close connection
mysql_close();
?>

INSERT INTO $users(email)VALUES('$email')
$users isn't a variable so will be empty when being placed into the table. I suspect you meant
$sql="INSERT INTO $tbl_name (email) VALUES ('$email')";
However you should never use unescaped user strings in queries since a malicious user could inject SQL into your query (read up on SQL Injection).
Also please be aware that the mysql_* series of functions is now deprecated, no longer maintained and will be removed in a future release of PHP. Consider mysqli or PDO.

Related

Why is my php script not dynamically populating an input field on my html form?

I am building an html form that will need to dynamically fill in the first input field with the "facility" column values in my "doctors" table. The facility column contains the names of our 7 offices. However, when I run the code below, my input field is blank and I have verified there is data in my "doctors" table. After this is working, I need to be able to dynamically fill in the second input field (which I haven't coded for in the code below because I'm stuck with the issue of first input) with the "provider" column values, also from my "doctors" table. The "provider" column contains all the provider names in our practice. However, the providers should be filtered, so that only the providers at the facility from the first input field is showing.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<?php
$link = mysqli_connect("localhost","USERNAME","PASSWORD");
mysqli_select_db($link,"DB");
?>
<head>
<title> Untitled Doc</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name "form1" action="" method="post">
<select>
<?php
$res=mysqli_query($link,"select facility from doctors");
while($row=mysqli_fetch_array($res)){?>
<option> <?php echo $row ["facility"]; ?></option>
<?php }?>
</select>
</form>
</body>
</html>
It is important that you check if the connection have been established, as I have copied your code as it is and use it on my side and was working fine, therefore made me suspect that the problem might be connection related. also check how sensitive your server is maybe your server see this as an error : $row ["facility"] that space might be the problem as well, but it didn't on my side.
Check your server error log and also enable error reporting at the top of your page add
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);?>
That will enable error reporting, but use that on local server only
Then on live site send them to error log
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
also to get the mysqli errors, before your connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Important to check if your query does indeed return results before trying to display them.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<?php
$link = mysqli_connect("localhost", "root", "", "DB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<head>
<title> Untitled Doc</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name ="form1" action="" method="post">
<?php
$query = "SELECT facility FROM doctors";
if ($res = mysqli_query($link, $query)) {
echo "<select name=\"myselect\">";
while ($row = mysqli_fetch_assoc($res)) {
?>
<option value="<?php echo $row['facility'];?>"><?php echo $row['facility'];?></option>
<?php
}
echo "</select>";
mysqli_free_result($res);
} else {
printf("Error : %s\n", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>
</form>
</body>
</html>
NB: For your own benefit, if you haven't used prepared statements, would suggest that you learn them as well, though they are not needed
in this case
When doing this kinda of query its important to catch errors so that you can debug easier. I have added a different way of connecting using mysqli object. Try this, this should determine if you have a connection error or if your query is not returning any results
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<?php
$link = new mysqli("localhost","USERNAME","PASSWORD", "DBNAME");
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<head>
<title> Untitled Doc</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name "form1" action="" method="post">
<select>
<?php
$res = $link->query("select facility from doctors");
// Check to see if query returned results
if($res->num_rows > 0 {
while($row = $res->fetch_assoc())
{
echo '<option>' . $row["facility"] . '</option>';
}
} else {
echo 'No results';
}
?>
</select>
</form>
</body>
</html>
Based on your code, when you want to access the data in a array you should put no space between the variable and the square brackets [] or your application will not show anything. In your code when you want to echo use
<option><?php echo $row["facility"]; ?></option>
instead of
<option><?php echo $row ["facility"]; ?></option>
For another case of the second field depends on the first field, i suggest to use JavaScript to get the data by sending the first data because it will reduce the processed of getting the data.
UPDATED:
To access your data, please add another parameter in your mysqli_fetch_array to be like this
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
this will make your data can be access using name on your table
<select>
<?php
$res=mysqli_query($link,"select facility from doctors");
while($row = $result->fetch_assoc($res))
{
?>
<option> <?php echo $row ["facility"]; ?></option>
<?php
}
?>
</select>

jQuery Mobile Form database update stopped working why

I need some help. I have been developing a form which updates a database. It was all working fine using the jQuery Mobile form and then suddenly it has all stopped working. I have stripped the form down the the bare minimum and still its not working. When I click on update the information is placed the the browser as shown below.
update_db.php?niamh=1
but the database is not updated. If I click on refresh it updates and displays success.
If I remove all the jQuery header links it all works ok, so this is a jQuery problem. Sadly this was all working ok a couple of hours ago. code below, can any one please help.
HTML form
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form action="update_db.php" method="GET">
<input type="checkbox" data-role="flipswitch" name="niamh" id="switch" value="1">
<input type="submit" data-inline="true" value="Update">
</form>
</body>
</html>
php update_db.php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="14Odiham"; // Mysql password
$db_name="heating"; // Database name
$tbl_name = "roomControl";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
// Insert data into mysql
$sql = "UPDATE $tbl_name SET niamh=$niamh WHERE id=1";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
<?php
//close connection
mysql_close();
?>
Try:
<form action="update_db.php" method="GET" data-ajax="false">

PHP - Recalling information stored in database using sessions

I've got problem when using sessions to recall data stored in mySQL database. This is my code:
The login page is simple, the input your username and password kind (i know the password is still plaintext, i plan to change it later).
<?php
$host="localhost";
$user="root";
$pass="";
$db_name="proyek";
$tbl_name="murid";
mysql_connect("$host", "$user", "$pass")or die("Cannot connect to SQL.");
mysql_select_db('$db_name');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="header">
LOGO
<h1 align="center">TITLE</h1>
</div>
<br/>
<div id="login">
<form id="loginform" name="loginform" method="post" action="checklogin.php">
<table border="0" align="center">
<tr>
<td>NIS</td>
<td></td>
<td><input type="text" name="nislogin" id="nislogin"/></td>
</tr>
<tr>
<td>Password</td>
<td></td>
<td><input type="password" name="pwdlogin" id="pwdlogin"/></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="loginbutton" id="loginbutton" value="Login"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
and this is the code for login check page:
<?php
session_start();
$host="localhost";
$user="root";
$pass="";
$db_name="proyek";
$tbl_name="murid";
mysql_connect("$host", "$user", "$pass")or die("Cannot connect to SQL.");
mysql_select_db('$db_name');
$nis=($_POST['nislogin']);
$pwd=($_POST['pwdlogin']);
$sql="SELECT * FROM murid WHERE nis='$nis' and password='$pwd'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
$_SESSION['nislogin']=$nis;
$nama=$result['nama'];
$_SESSION['nama']=$nama;
header("location:index.php");
return true;
exit;
}
else
{
echo("Wrong NIS or password.");
return false;
}
?>
i have entered some dummy data in database for testing purposes; id, password, name. how can i recall something from database while user only login with username/id?
i'd like to display something like 'hello, name' in the next page. Help is appreciated.
edit: I've edited my code based on feedbacks and it produces blank; like 'Hello,' with no name.
First of all, since you are running a query on your login check page, use that value for your session rather than the post data. Also, whenever you are redirecting, always exit your script.
EDIT:
Since you are in the development stage, you need to display an error if your query fails so you know why. I also realized you need to return an associative array to access the row. Try this.
$sql="SELECT * FROM murid WHERE nis='$nis' and password='$pwd'";
$result=mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$count=mysql_num_rows($result);
if($count==1)
{
$data=mysql_fetch_assoc($result); // since you are only accessing one row,
// otherwise you would put this in a loop to build your array.
session_start();
$_SESSION['nislogin']=$data['nis'];
header("location:index.php");
return true;
exit;
}
I also see this session on your login page, but I don't see that you ever created it and I don't see the purpose.
if(isset($_SESSION['nama']))
{
unset($_SESSION['nama']);
}
Basically all you need from here, is to start the session on index.php and output it.
index.php
session_start();
if(isset($_SESSION['nislogin']))
{
$name = $_SESSION['nislogin'];
} else {
$name = "stranger";
}
<body>
Welcome, <?=$name?>
</body>

PHP update sql record

Somehow I get my sql error while trying to update a record in my sql db
Here's my current code
html form:
<html>
<head>
<title>title here</title>
</head>
<body>
<form action="end.php" method="POST">
<input type="text" id="comment" name="comment" placeholder="Kommentar"><p>
<input type="submit" value="Stop arbejde">
</form>
</body>
</html>
end.php
<?php
$host="localhost";
$username="root";
$password="password";
$db_name="db";
$tbl_name="log";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$comment=$_POST['comment'];
$datetime=date("y/m/d H:i:s");
$editit=date("W/D");
$sql="UPDATE log SET end=$datetime, comment=$comment WHERE editid='$editit'";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
}
else {
echo "Fejl";
}
mysql_close();
?>
What am I doing wrong since I get that error "Fejl" ?
string must be wrap with single quotes
$sql="UPDATE log SET end='$datetime', comment='$comment' WHERE editid='$editit'";
but your query is prone to SQL Injection. please take time to read the article below
How can I prevent SQL injection in PHP?
The variable names in $sql should be inside single inverted comas.
$sql="UPDATE log SET end='$datetime', comment='$comment' WHERE editid='$editit'";
And also, you should remove paragraph tag from html code in form tag.

PHP login not working - user still sees the login form on protected pages after logging in

------ SOLVED ------
Hi everyone, I have now solved this issue and it was my inexperience and trying to be clever that caused this issue, as you can also see from the comments below the issue was in my .htaccess file. I had put RewriteRule ^admin adminlogin.php so this was changing any page containing admin back to adminlogin.php
------ORIGINAL QUESTION------
Im trying to get a simple login script working on a website. It is coded in php and it is as follows:
adminlogin:
<div class="login">
<form name="form1" method="post" action="checklogin.php">
<table width="379px" border="0px" cellpadding="3px" cellspacing="1px">
<tr>
<td colspan="3"><strong>Admin Login</strong></td>
</tr>
<tr>
<td width="78px">Username</td>
<td width="6px">:</td>
<td width="294px"><input name="myusername" type="text"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</div>
checklogin.php:
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name="Logins"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die(mysql_error());
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM `$tbl_name` WHERE UN='$myusername' and PWD=md5('$mypassword')";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file “adminloginsuccess.php"
session_start();
$_SESSION['user'] = $myusername;
header('location:adminhome.php');
}
else {
header('location:adminloginretry.php');
}
?>
adminhome.php:
<?php $thisPage="Admin Home";
session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/meta.php'); ?>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="header">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/header.php'); ?>
<div id="links">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/links.php'); ?>
</div><!--close links-->
</div><!--close header-->
<div id="sidebar">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/sidebarimage.php'); ?>
</div><!--close sidebar-->
<div id="content">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/adminhomecontent.php'); ?>
</div><!--close content-->
<div id="extra" align="center">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/fblb.php'); ?>
</div><!--close extra-->
<div id="footer">
<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/footer.php'); ?>
</div><!--close footer-->
</div><!--close container-->
</div><!--close wrapper-->
</body>
</html>
adminhomecontent.php:
You Have Successfully Logged In.<br>
Log Out
Now for some reason when I go and log in, I am redirected and the address bar says www.gemma-hyde-fashion-sketches.co.cc/adminhome.php but still shows the login form, and if I view the source I see the source for adminlogin.php.
I am new to PHP, could anybody assist, I found this code online so have tried myself to understand it as fully as I can
------EDIT------
I have created a log in for stackoverflow users. If you head over to www.gemma-hyde-fashion-sketches.co.cc/adminlogin.php and use the username stackoverflow and the password stackoverflow you should see the same results i'm getting (there isnt actually anything in the admin area at this time anyway)
------EDIT FOR JUDDA------
Yes what I mean is that if I log in, the address bar shows: http://www.gemma-hyde-fashion-sketches.co.cc/adminhome.php which is what i expected to be redirected to. However if i right click and view source I see
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gemma Hyde Fashion Sketches | Admin Login</title>
<meta name="title" content="Gemma Hyde Fashion Sketches | Admin Login" />
<meta name="keywords" content="Admin Login, gemma hyde fashion sketches, fashion, fashion design, fashion sketches, fashion design sketches, clothes design sketches" />
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
which is the same as what the adminlogin.php page would show, this makes me think that this section at the top of adminhome.php:
session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
}
Is just redirecting because it cannot pick up that it is logged in.
Does that clear things up?
It sounds to me like PHP isn't running on the file if you are able to see the actual PHP for it (which I understand from the statement "and if I view the source I see the source for adminlogin.php"). Do other PHP pages work (i.e. <?php phpinfo();?>)?
If you suspect the session is not set check that in adminhome.php
Change this code
Session_start();
if(!(isset($_SESSION['user']) && $_SESSION['user'] != '')) {
header("location:adminlogin.php");
to this
Session_start();
exit(var_dump($_SESSION));
I have now solved this issue and it was my inexperience and trying to be clever that caused this issue, as you can also see from the comments below the issue was in my .htaccess file. I had put RewriteRule ^admin adminlogin.php so this was changing any page containing admin back to adminlogin.php

Categories