How do I alter the following code to allow me to extract data from another table (data2), and post it as I did the others(name,position,bio). Basically I want another form field that I can search from to find an item from another table, and add into this one.
<?php
require 'db/connect.php';
$error = ""; //variable to hold our form error message
$success = ""; //variable to hold our success message
if(isset($_POST['create'])){
$name = trim($_POST['name']);
$position = trim($_POST['position']);
$bio = trim($_POST['bio']);
if(empty($name) && empty($position) && empty($bio)){
$error = "You must fill all fields.";
}else{
$insert = $db->prepare("INSERT INTO staff (name, position, bio, joined) VALUES (?, ?, ?, NOW())");
$insert->bind_param(sss, $name, $position, $bio);
if($insert->execute()){
//$success = "Staff added successfully!";
header("location:index.php");
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="wrapper">
<h1>Create New Staff</h1>
<span class="error"><?php if(isset($error)) echo $error;?></span>
<span class="success"><?php if(isset($success)) echo $success;?> </span>
<form action="" method="post">
<table class="table">
<tr>
<td><label for="name">Name:</label></td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td><label for="position">Position:</label></td>
<td><input type="text" id="position" name="position"></td>
</tr>
<tr>
<td><label for="bio">Bio:</label></td>
<td><textarea id="bio" name="bio"></textarea></td>
</tr>
<tr>
<td></td>
<td><button type="submit" class="create" name="create">CREATE</button> <a class="btn" href="index.php">BACK</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Well you could have in the table that the form submits to a location_id that is a key linked to the locations table.
Then all you need to do is do an sql query where you select values using LIKE (see MySQL LIKE - I think w3schools covers this well)
You could call this function in Ajax to check every key press.
Alternatively load all the locations to a hidden element and when the input is focused they appear and as you type you use JavaScript to hide those that don't match.
I would write an example but I'm on my phone. Hope this helps a little.
Related
EDIT: The code now works. Added some code to the initial source code below.
So I have a database named payload and in it there's two tables; one named users and the other named tohere. Both of these tables just have two columns; userName and password. The tohere table is empty. The users table, however, has two populated rows. First row has admin and admin123 as the userName and password respectively. The second row has visitor and visitor123 as the userName and password respectively. There's a HTML form with two input fields where users enter a username and password. Now the idea is, if the username and password they enter in the form matches the records in the users table, I want those contents submitted to the tohere table which is currently empty. How do I accomplish that?
I have tried the following code which doesn't seem to work;
<html>
<head>
<title>
</title>
<?php
$message = "";
$theusername = $_POST['userName'];
$thepass = $_POST['password'];
if (count($_POST) >
0) {
$conn = mysqli_connect("localhost", "root", "", "payload");
$result = mysqli_query($conn, "SELECT * FROM users WHERE userName='" . $_POST["userName"] . "' and password = '" . $_POST["password"] . "'");
$count = mysqli_num_rows($result);
if ($count == 0) {
$message = "Invalid Username or Password!";
} else {
$sqltwo = "INSERT INTO tohere (userName, password) VALUES ('$theusername', '$thepass')";
//The below if statement was missing.
if(!mysqli_query($conn, $sqltwo)){
echo "Failed!";
}
else{
echo "Success!";
}
}
}
?>
</head>
<body>
<form action="" method="post" name="frmUser">
<div class="message">
<?php if ($message != "") {echo $message;}?>
</div>
<table align="center" border="0" cellpadding="10" cellspacing="1" class="tblLogin" width="500">
<tr class="tableheader">
<td align="center" colspan="2">
Enter Login Details
</td>
</tr>
<tr class="tablerow">
<td>
<input class="login-input" name="userName" placeholder="User Name" type="text"/>
</td>
</tr>
<tr class="tablerow">
<td>
<input class="login-input" name="password" placeholder="Password" type="password"/>
</td>
</tr>
<tr class="tableheader">
<td align="center" colspan="2">
<input class="btnSubmit" name="submit" type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
</body>
</html>
So far, this code works, but only partially. When I enter username and password not in the users table, I get the message "Invalid Username or Password!", which is fine, but when I enter records that are in the users table, the form does not get submitted to the tohere table. In fact, nothing happens. Just a blank white screen. What gives?
Hey and thanks in advance, I'm trying to get data from a form and enter it into a database. I'm following a guide on how to do this, but the guide doesnt account for anything not working........
I've only just started out with PHP so my skills are quite limited, however I do understand all code I have written, it just doesn't work! The php script will not move past the if statement below and I can't figure out why:
// Check for existing user with the new id
$sql = "SELECT COUNT(*) FROM sessions.users WHERE userid = '$_POST[newid]'";
$result = mysqli_query($cxn, $sql);
if (!$result) {
error('A database error occurred in processing your '.
'submission.\nIf this error persists, please '.
'contact you#example.com. This is from error 1');
Entire code:
signup.php
<?php //signup.php
include 'common.php';
include 'db.php';
if(!isset($_POST['submitok'])):
// display user signup form
?>
<!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>New User Registration</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h3>New User Registration Form</h3>
<p><font color="orangered" size="+1"><tt><b>*</b></tt></font> indicates a required field</p>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<table border="0" cellpadding="0" cellspacing="5">
<tr>
<td align="right">
<p>User ID</p>
</td>
<td>
<input name="newid" type="text" maxlength="100" size="25" />
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr>
<td align="right">
<p>Full Name</p>
</td>
<td>
<input name="newname" type="text" maxlength="100" size="25" />
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr>
<td align="right">
<p>E-Mail Address</p>
</td>
<td>
<input name="newemail" type="text" maxlength="100" size="25" />
<font color="orangered" size="+1"><tt><b>*</b></tt></font>
</td>
</tr>
<tr valign="top">
<td align="right">
<p>Other Notes</p>
</td>
<td>
<textarea wrap="soft" name="newnotes" rows="5" cols="30"></textarea>
</td>
</tr>
<tr>
<td align="right" colspan="2">
<hr noshade="noshade" />
<input type="reset" value="Reset Form" />
<input type="submit" name="submitok" value=" OK " />
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
else:
//process sign up submission
dbConnect('sessions');
if ($_POST['newid']=='' or $_POST['newname']==''
or $_POST['newemail']=='') {
error('One or more required fields were left blank.\\n'.
'Please fill them in and try again.');
}
// Check for existing user with the new id
$sql = "SELECT COUNT(*) FROM sessions.users WHERE userid = '$_POST[newid]'";
$result = mysqli_query($cxn, $sql);
if (!$result) {
error('A database error occurred in processing your '.
'submission.\nIf this error persists, please '.
'contact you#example.com. This is from error 1');
}
if (#mysqli_result($result,0,0)>0) {
error('A user already exists with your chosen userid.\n'.
'Please try another.');
}
$newpass = substr(md5(time()),0,6);
$sql = "INSERT INTO sessions.users SET
userid = '$_POST[newid]',
password = PASSWORD('$newpass'),
fullname = '$_POST[newname]',
email = '$_POST[newemail]',
notes = '$_POST[newnotes]'";
if (!mysqli_query($sql))
error('A database error occurred in processing your '.
'submission.\nIf this error persists, please '.
'contact you#example.com. This is from error 2');
// Email the new password to the person.
$message = "G'Day!
Your personal account for the Project Web Site
has been created! To log in, proceed to the
following address:
http://www.example.com/
Your personal login ID and password are as
follows:
userid: $_POST[newid]
password: $newpass
You aren't stuck with this password! Your can
change it at any time after you have logged in.
If you have any problems, feel free to contact me at
<you#example.com>.
-Your Name
Your Site Webmaster
";
mail($_POST['newemail'],"Your Password for the Project Website",
$message, "From:Your Name <you#example.com>");
?>
<!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> Registration Complete </title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1" />
</head>
<body>
<p><strong>User registration successful!</strong></p>
<p>Your userid and password have been emailed to
<strong><?=$_POST['newemail']?></strong>, the email address
you just provided in your registration form. To log in,
click here to return to the login
page, and enter your new personal userid and password.</p>
</body>
</html>
<?php
endif;
?>
db.php
<?php // db.php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
function dbConnect($db='') {
global $dbhost, $dbuser, $dbpass;
$cxn = mysqli_connect($dbhost,$dbuser,$dbpass);
mysqli_select_db($cxn,$db)
or die ("Couldn’t select database.");
return $cxn;
}
?>
common.php
<?php // common.php
function error($msg) {
?>
<html>
<head>
<script language="JavaScript">
<!--
alert("<?=$msg?>");
history.back();
//-->
</script>
</head>
<body>
</body>
</html>
<?php
exit;
}
?>
Any help as to why this if statement ALWAYS produces the error would be grand - thank you.
You're not assigning your db connection within a usable scope. You are returning it from your dbConnect() function, you're just not doing anything with the returned value.
dbConnect('sessions'); should be $cxn = dbConnect('sessions');
You would be alerted to the cause of the problem if you used mysqli_error() to let MySQL tell you what it didn't like.
Finally, you should be using bound parameters in your query instead of injecting user-provided data directly. Search something like "mysqli bound parameters" to learn how to do this. What you have now is open to attack.
For your INSERT statement, use bound parameters:
$sql = "INSERT INTO sessions.users (userid, password, fullname, email, notes) VALUES (?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($sql);
mysqli_stmt_bind_param($stmt, 'issss', $newID, PASSWORD($newpass), $fullName, $email, $notes);
if(!mysqli_stmt_execute($stmt))
{
// use this for debugging, but do NOT leave it in production code
die(mysqli_error($cxn));
}
mysqli_stmt_close($stmt);
Above is untested so it's possible you'll have to make small adjustments. It should give you a pretty good idea of what to do at least.
Also, make sure that PASSWORD() is really what you want to be using. I have a feeling it's not, but I don't want to assume.
I have created 2 tables for phpMyAdmin. One of them is countries and the other is the users.
Countries table:
Users table:
I know how to create forms with HTML and PHP. I want my users to select a country, but the countries are in the different table and cannot be placed in the users table. Would I need to link it up by using the 'SQL' section on phpMyAdmin or is there a PHP code for it?
I haven't fully constructed the php form yet(just started!)
<h1>Register</h1>
<form action="" method="POST">
<p>
<label>UserName : </label>
<input id="username" type="text" name="usernamet" placeholder="Username" />
</p>
<input id="teamname" type="text" name="username" placeholder="Team Name" />
</p>
<select name="countries">
<option value="England">Volvo</option>
<option value="Spain">Saab</option>
<option value="Turkey">Fiat</option>
<option value="France">Audi</option>
</select>
<p>
<label>E-Mail :</label>
<input id="password" type="email" name="email" />
</p>
<p>
<label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" />
</p>
<a class="btn" href="login.php">Login</a>
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
Okay... here goes my answer.
As I said, if you plan on asking for a user country, you HAVE to have a place to store it in that same table but if you plan on storing it in another table, that is fine too but you will need to change my single query insert into two query inserts. One to go into a table for your user information and the other to go into the table with the information that will hold the user ID# from the users table (or the id column) and the value from the form.
Original Table:
New Table that I'm working with:
This form also includes error handling options like a blank form. If you want to validate email addresses and the like, search around for a function that will do just that and throw a handler in the verification section below. Also this code assumes you want the form to be processed on its self, that is the form and the code to process the form reside on the same script page. If you plan on doing anything besides, edit the <form action= and remove the <?php ... ?> coding from it. If you want to remove any of this, delete the lines of code related to that.
Also note that this script is using mysqli_ functions and not mysql_ functions as mysql_ and related functions are considered deprecated and will eventually be removed from PHP as of PHP 5.4 (I believe.)
If you don't want confirmation pages, you can edit the script to do just that for you. If you need anything else, edit your original question.
Your problem with the going through the countries list is resolved simply by performing a SELECT * query and then proceeding to loop through the results of that query and adding them to an array as I did. In this case, I used a while() loop to cycle through the results of the array returned from the mysqli_query() function and added the formatted results to an array that will eventually be outputted to the form.
<?php
//Define MySQLi connection information
$db = mysqli_connect("localhost", "stackoverflow", "", "stackoverflow");
// mysqli_connect(SERVER_ADDR, DB_USER, DB_PASSWORD, DB_NAME)
if (mysqli_connect_errno()) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
if(isset($_POST) && sizeof($_POST) > 0 ) {
// If there is something to post, start this branch
$username = mysqli_real_escape_string($db, $_POST['username']);
$teamname = mysqli_real_escape_string($db, $_POST['teamname']);
$usercountry = mysqli_real_escape_string($db, $_POST['countries']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
// Check to make sure we have a valid form.
// If you need more, follow the same pattern.
if (empty($username) || empty($_POST['username'])) $error[] = "Username cannot be empty.";
if (empty($email) || empty($_POST['email'])) $error[] = "Email Address cannot be empty.";
if (empty($password) || empty($_POST['password'])) $error[] = "Password cannot be blank.";
if (empty($usercountry) || empty($_POST['countries'])) $error[] = "Please select a country from the drop down list.";
if (!isset($error)) {
// No errors? No problem. Insert the form data into the database.
$user_insert = "INSERT INTO users (username, teamname, country, email, password, active, rank) VALUES ('" . $username . "' , '" . $teamname . "', '" . $usercountry ."', '" . $email ."', PASSWORD('" . $password . "'), 1, 1)";
mysqli_query($db, $user_insert);
}
} ?>
<?php if (isset($error) || empty($_POST)) {
// There was noting to post, so show the form to collect the information.
// Retrieve the values from the countries table.
$countries = mysqli_query($db, "SELECT * FROM countries ORDER BY countryName");
$country_options = array();
$country_options[] = array('value' => '', 'text' => '');
while($row= mysqli_fetch_array($countries)) {
$country_options[] = array('value' => $row['idCountry'], 'text' => $row['countryName']);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>User Registration Form</title>
<!-- include your <style> CSS or imports here -->
<style>
.leftCell {
width: 160px;
}
.error {
border: 1px solid #FF0000;
background-color: #FFCCCC;
color: #FF0000;
padding: 10px;
</style>
</head>
<body>
<?php if (isset($error)) { ?>
<div class="error">
<b>Please fix the following errors:</b>
<ul>
<?php foreach($error as $error_text) {
echo "<li>" . $error_text . "</li>";
}
?>
</ul>
</div>
<?php } ?>
<!-- assuming you do not already have a script to input the data, I'm using this page to input the data -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<!-- Let's create a table -->
<h1>Register</h1>
<table>
<tr>
<td class="leftCell">Desired User Name:</td>
<td><input id="username" type="text" name="username" placeholder="Username" value="<?php echo (isset($username) ? $username : ''); ?>"/></td>
</tr>
<tr>
<td class="leftCell">Team Name:</td>
<td><input id="teamname" type="text" name="teamname" placeholder="Team Name" value="<?php echo (isset($teamname) ? $teamname : ''); ?>"/></td>
</tr>
<tr>
<td style="width: 50px;">User Country:</td>
<td><select name="countries">
<?php
foreach($country_options as $country) {
echo '<option value="' . $country['value'] . '" ' . ($country['value'] == $usercountry ? 'selected="selected"' : '') . '>' . $country['text'] . "</option>";
}
?>
</select></td>
</tr>
<tr>
<td class="leftCell">E-Mail:</td>
<td><input id="email" type="text" name="email" placeholder="E-Mail" /></td>
</tr>
<tr>
<td class="leftCell">Password:</td>
<td><input id="password" type="password" name="password" placeholder="Password" /></td>
</tr>
</table>
<a class="btn" href="login.php">Login</a><br />
<input class="btn register" type="submit" name="submit" value="Register" />
</form>
</body>
</html>
<?php } else { ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>User Registration - Success</title>
</head>
<body>
<h1>The user was successfully registered!</h1>
</body>
</html>
<?php } ?>
I have a php page that connects to a mysql database. I know that the connection to the database is good because I have a php code that displays info from the database onto the webpage. When I try to insert new data into the databse, the page refreshes and the data is not inserted. I have checked to insure that the insert into command has the correct values.
<?php
if (isset($_POST['User_Name']))
{
include "connect_to_mysql.php";
$name = mysql_real_escape_string($_POST["Name"]);
$sql = mysql_query("SELECT TestID FROM test WHERE Name='$name' LIMIT 1")or die (mysql_error());
$productMatch = mysql_num_rows($sql);
if ($productMatch > 0)
{
echo 'Sorry you tried to place a duplicate "User Account" into the system, click here';
exit();
}
else
{
$sql = mysql_query("INSERT INTO test (TestID,Name)
VALUES('', '$name')") or die (mysql_error());
$uid = mysql_insert_id();
header("location: index.php");
exit();
}
}
?>
<?php
include "connect_to_mysql.php";
$User_list = "";
$sql = mysql_query("SELECT * FROM test");
$UserCount = mysql_num_rows($sql);
if ($UserCount > 0)
{
while($row = mysql_fetch_array($sql))
{
$id = $row["TestID"];
$name = $row["Name"];
$User_list .= "Users ID: $id - <strong>$name</strong> <br />";
}
}
else
{
$User_list = "You have no users listed in the database.";
}
?>
<!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>Untitled Document</title>
</head>
<body>
<div align="center" id="mainWrapper">
<div id="pageContent"><br />
<div align="right" style="margin-right:32px;">+ Add New User</div>
<div align="left" style="margin-left:24px;">
<h2>User list</h2>
<?php echo $User_list; ?>
</div>
<hr />
<a name="UserForm" id="UserForm"></a>
<h3>
↓ Add New User Form ↓
</h3>
<form action="index.php" enctype="multipart/form-data" name="myForm" id="myform" method="post">
<table width="90%" border="0" cellspacing="0" cellpadding="6">
<tr>
<td width="20%" align="right">Name</td>
<td width="80%"><label>
<input name="name" type="text" id="name" size="50" />
</label></td>
</tr>
<tr>
<td> </td>
<td><label>
<input type="submit" name="button" id="button" value="Add This Name Now" />
</label></td>
</tr>
</table>
</form>
<br />
<br />
</div>
</div>
</body>
</html>
I see two problems right away (there may be more). First, PHP array keys are case sensitive. You are accessing $_POST['Name'] but your form input is name. Second, you are testing for $_POST['User_Name'] which doesn't appear to exist anywhere:
// Look for name in the $_POST
if (isset($_POST['name']))
{
include "connect_to_mysql.php";
// name is case-sensitive
$name = mysql_real_escape_string($_POST["name"]);
Later, if your table has an AUTO_INCREMENT id on TestID, you should either omit it or insert NULL in the insert statment:
// Don't include TestID if it is AUTO_INCREMENT. That will happen automatically
$sql = mysql_query("INSERT INTO test (Name)
VALUES('$name')") or die (mysql_error());
I think it will work if you change
if (isset($_POST['User_Name']))
to
if (isset($_POST['Name']))
You check the existence of something which doesn't exists in your form.
Addition:
If TestID is autoincrement, change the below
"INSERT INTO test (TestID,Name) VALUES('', '$name')"
to
"INSERT INTO test (Name) VALUES('$name')"
If you do not get any errors that means you have an error in your MySQL syntax two ways to test it would be to copy the syntax into PHPMyAdmin or whatever your native MySQL command line is and see if you get an output error. Or another thing you can do is to modify all your mysql_query(); functions by adding mysql_query()or die(mysql_error());
I have been trying to make a login system via PHP. When I try to run it, all code from ($errors as $error) is shown on the actual webpage. I've been trying to test it for a few hours.
Note: When I change the > to <, it works fine in if(count($errors) > 0){
but that makes it so even if there are errors with passwords/usernames they can still press enter.
Any help please! Code is provided.
<?
mysql_pconnect('localhost', 'root', '');
?>
<!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>Login</title>
</head>
<body>
<?php
if(!$_POST['submit']) {
?>
<form action="index.php" method="post">
<table border="1">
<tr>
<td>
Username:
</td>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="text" name="password" />
</td>
</tr>
<tr>
<td>
Retype Password:
</td>
<td>
<input type="text" name="passwordconf" />
</td>
</tr>
<tr>
<td>
Email Address:
</td>
<td>
<input type="text" name="email" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Create User" name="submit" />
</td>
</tr>
</table>
</form>
<?php
} else {
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST ['passwordconf'];
$email = $_POST ['email'];
$errors = array();
if(!$username) {
$errors[1] = "Please enter a username.";
}
if(!$password) {
$errors[2] = "Please enter a password.";
}
if(!$passwordconf) {
$errors[3] = "Please retype password.";
}
if(!$email) {
$errors[4] = "Please enter an email address.";
}
if($password != $passwordconf) {
$errors[5] = "Passwords do not match.";
}
if(count($errors) > 0){
foreach($errors as $error) {
echo "$error<br>";
}
} else {
mysql_query("INSERT INTO 'users' . 'user_info'
('username', 'password', 'email', 'user_admin_level')
VALUES ('".$username."', '".md5($password)."', '".$email."', '1');");
}
}
?>
</body>
</html>
You can't run PHP like that. You need web server to run PHP. Follow these steps,
Using XAMPP is very easy. Follow these steps -
Install and run the XAMPP application. Turn on Apache & MySQL (if your application needs database) services through it.
Click on 'Explore' button on the XAMPP control panel - in the window that opens, check for htdocs folder.
htdocs folder is the one where all your PHP scripts should lie. This is the folder that Apache points to.
You might want to create a separate folder inside /htdocs/ folder to save all your PHP programs. Let's call it 'myprograms'.
Save your php script in /htdocs/myprograms folder. (Ex. test.php)
Now, start your webbrowser and type following address: http://localhost/myprograms/test.php
Your browser will now execute the script and show you the output.
from URL :file:///C:/Users/User/Desktop/LoginSystem.php you are accessing a file which will not be interpreted by the PHP Interpreter (wamp or lamp).
You need to install a php server(wamp, xamp or Lamp ) and put your file in respective webserver directories then execute you file by entering url like this :
localhost/LoginSystem.php
Hope this will help
You cannot call PHP-files without a webserver serving them. PHP is the acronym for "PHP Hyptertext Preprocessor", which implies that there is a preprocessor needed to interpret those files.
Try using XAMPP, that's a lightweight server system that comes with an apache web-server, a mySQL-server and PHP- and PERL-support.
When using XAMPP already put your php-file into the htdocs-folder of your XAMPP-installation and then call http://localhost/yourscript.php.
#Rick Roll'd
open your php page like this
http://localhost/path_to_page/LoginSystem.php
Don't store your page on Desktop save php page in www/htdocs directory.
try displaying $errors and the size (print_r($errors); echo count($errors);) to see if it really has no content.
Also I'd change if(!$username) to if (empty($username))
+ it's very bad practice to accept userinput as $var = $_POST['varname'].
Also an array always starts with key 0 (you're manually assigning it to key 1). To simply add elements to an array use $errors[] = "you forgot something";
Personally I'd advise you to choose a login/session class from a project like Drupal/cakePHP/phpBB/...
Maybe you should place the HTML code first. An empty field is not always an error. For example:
<!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>Login</title>
</head>
<body>
<form action= "<?php $_SERVER[ 'PHP_SELF' ] ?>" method="post">
<table border="1">
<tr>
<td>
Username: </td>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<td>
Password: </td>
<td>
<input type="text" name="password" />
</td>
</tr>
<tr>
<td>
Retype Password: </td>
<td>
<input type="text" name="passwordconf" />
</td>
</tr>
<tr>
<td>
Email Address: </td>
<td>
<input type="text" name="email" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Create User" name="submit" />
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
if ( isset ( $_POST[ 'submit' ] ) ) {
if ( $_POST[ 'username' ] ) {
$username = $_POST[ 'username' ];
$username = trim( $username) ; // Remove spaces
}
else {
echo "Please enter a username.<br /><br />";
die;
}
// And so on....
mysql_pconnect( 'localhost', 'root', '' );
mysql_query( "INSERT INTO 'users' . 'user_info'
('username', 'password', 'email', 'user_admin_level')
VALUES ('" . $username . "', '" . md5( $password ) . "', '" . $email . "', '1');" );
}
?>
You can test it installing a local server, as suggested, or uploading the file to your ISP server.
Hope this helps.