How to link up the tables in MySQL - php

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

Related

Connection phpmyadmin and html

Greeting dear programmers, i have problem in connecting mydatabase. I create three tables under one database. I put relationship for three table. After i put it i add phpcode to connect it. But it doesnt want to work. Before this,i try connect use that code. It works. But for this it doesnt want. I dont know is it because of the table relationship or got any error on my html form. Any developer pls help me to tell my problem. A lot of Thanks in advance.
<?php
session_start();
$_SESSION['message'] = '';
$mysqli=new MySQLi('127.0.0.1','root','','accounts');
if($_SERVER["REQUEST_METHOD"] == "POST") {
$option1 = $_POST['option1'];
$option2 = $_POST['option2'];
$option3 = $_POST['option3'];
$option4 = $_POST['option4'];
$option5 = $_POST['option5'];
$option6 = $_POST['option6'];
$sql ="INSERT INTO menubar(option1,option2,option3,option4,option5,option6)"
."VALUES ('$option1','$option2','$option3','$option4','$option5','$option6')";
if($mysqli->query($sql)=== true) {
$_SESSION['message'] ='Registration successful!
Added to the database!';
header("location:confirmnormal.php");
}
else {
$_SESSION['message'] = "User could not be added to 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>Normal</title>
</head>
<body>
<div>
<?=$_SESSION['message']?>
<table align="center" >
<form method="post" action="" enctype="multipart/form-data" autocomplete="off">
<tr>
<td>
Enter Menu Bar:
</td>
<td>
<input type="text" placeholder="Personal Information" name="option1" required/>
<tr><td></td><td>
<input type="text" placeholder="Career Aspirations" name="option2" required />
</td></tr>
<tr><td></td><td>
<input type="text" placeholder="Educational Background" name="option3" required />
</td></tr>
<tr><td></td> <td> <input type="text" placeholder="Skills" name="option4" required /></td></tr>
<tr><td></td> <td><input type="text" placeholder="Language Proficiency" name="option5" required /></td></tr>
<tr><td></td><td><input type="text" placeholder="Job Preference" name="option6" required /></td>
</tr>
<tr>
<td align="center">
<input type="submit" name="login" value="register" class="btn-login"/>
</td>
</tr>
</tr>
</tr>
</form>
</table>
</div>
</body>
</html>
Check the POST using isset() also check the POST by using form submit
if(isset($_POST['submit']))
{
$option1 = $_POST['option1'];
$option2 = $_POST['option2'];
$option3 = $_POST['option3'];
$option4 = $_POST['option4'];
$option5 = $_POST['option5'];
$option6 = $_POST['option6'];
$sql ="INSERT INTO menubar(option1,option2,option3,option4,option5,option6)"
."VALUES ('$option1','$option2','$option3','$option4','$option5','$option6')";
if($mysqli->query($sql)=== true) {
$_SESSION['message'] ='Registration successful!
Added to the database!';
header("location:confirmnormal.php");
}
else {
$_SESSION['message'] = "User could not be added to the database!";
}
}

PHP Registration form not cheking if username exists

I'm writing a code for a simple registration system. I have this part where I check if the username or email already exist. If this is the case, it should show an error message, but it doesn't work. If the username or email exist, the registration form is submitted anyway.
This is my code
Registration.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" href="favicon.png" type="image/x-icon"/>
<link rel="icon" type="image/png" href="favicon.png" />
<title>Registro</title>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$mysqli = NEW
MySQLi('localhost','user','pass','database');
$username = $_POST['username'];
$name = $_POST['name'];
$pass= $_POST['pass'];
$email= $_POST['email'];
$phone= $_POST['phone'];
$querya=mysqli_query($mysqli,"select * from table where username='$username' && email='$email'");
$num_rowss=mysqli_num_rows($querya);
if ($num_rowss>0){
echo "Username or password is taken, please write a new one."
}else{
$query = "INSERT INTO table(username,name,pass,email,phone)VALUES('"
. $mysqli->real_escape_string($username) .
"' , '"
. $mysqli->real_escape_string($name) .
"' , '"
. $mysqli->real_escape_string($pass) .
"' , '"
. $mysqli->real_escape_string($email) .
"' , '"
. $mysqli->real_escape_string($phone) .
"')
";
$insert = $mysqli->query($query);
if($insert){
header('Location: login.php');
}
}
$mysqli->close();
}
?>
<div>
<h1>Register</h1>
<form action="" method="post" name="registro" id="formulario"><br><br>
<table>
<tr><td>Username: <input type="text" name="username" id="username" required></td>
</tr>
<tr><td>Name:<input type="text" name="name" id="name" required></td>
</tr>
<tr><td>Password: <input type="password" name="pass" required></td>
</tr>
<tr><td>Email: <input type="email" name="email" required></td>
</tr>
<tr><td>Phone: <input type="text" name="phone" required></td>
</tr>
<tr><td> <input name="submit" id="submit" type="submit" value="Registrar" /></td></tr>
</table><br><br>
</form>
</div>
</body>
A couple things:
Concern on SQL Injection - Use Parameters
It should be OR, NOT &&. You want to know if the username or e-mail is found.
You should have some way to handle errors also.
Your query should read as the following:
$querya=mysqli_query($mysqli,"select * from table where username='$username' OR email='$email'");
$num_rowss=mysqli_num_rows($querya);
Try this. it works for me sorry if not!
$querya = "SELECT username, email FROM table WHERE username = '".$name."' OR email = '".$email."'";
$result = $mysqli->query($sql);
if(mysqli_num_rows($result) > 0)
{
echo 'Username or password is taken, please write a new one.';
}
else
{

SQL PHP Searchable Form Field Add To New Database

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.

blank screen when login

I need some help with my code. It works on XAMPP on my computer but when it's live on my server it won't work all I get is a blank screen. You can have a look what happens at <a href="http://www.redhotessentials.com/prototype/pages/login.php</a> put username allanallan password allanallan and you can see what happens thanks
<?php
if (isset($_POST['email'])) {
//Connect to the database through our include
require("db.php");
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']); // filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM members WHERE email='$email' AND password='$password' AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check>0){
while($row = mysql_fetch_array($sql)){
// Get member ID into a session variable
$id = $row['id'];
session_register('id');
$_SESSION['id'] = $id;
// Get member username into a session variable
$username = $row['username'];
session_register('username');
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE members SET lastlogin=now() WHERE id='$id'");
// Print success message here if all went well then exit the script
header("location: endlessnails_blog.php");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again </font><br />
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login to your profile</title>
<link rel="stylesheet" type="text/css" href="../../css/main4.css" />
<script type="text/javascript">
<!-- Form Validation -->
function validate_form ( ) {
valid = true;
if ( document.logform.email.value == "" ) {
alert ( "Please enter your User Name" );
valid = false;
}
if ( document.logform.pass.value == "" ) {
alert ( "Please enter your password" );
valid = false;
}
return valid;
}
<!-- Form Validation -->
</script>
</head>
<?php include("header.php"); ?>
<?php include("nav.php"); ?>
<body>
<div id="container">
<div id="box3">
<div align="center">
<h3 id="login2"><br />
<br />
Log into Endless Nails Blog<br />
<br />
</h3>
</div>
<div id="loginformmove">
<table class="style7" align="center" cellpadding="5">
<form action="index.php" method="post" enctype="multipart/form-data" name="logform"
id="logform" onsubmit="return validate_form ( );">
<tr>
<td class="style7"><div align="right">Email Address:</div></td>
<td class="style7"><input name="email" type="text" id="email" size="30" maxlength="64" /></td>
</tr>
<tr>
<td class="style7"><div align="right">Password:</div></td>
<td class="style7"><input name="password" type="password" id="password" size="30" maxlength="24" /></td>
</tr>
<tr>
<td class="style7"> </td>
<td id="login3"><input name="Submit" type="submit" value="Login" class="login_pad" /></td>
</tr>
</form>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
Remove the enctype from your FORM attributes, since you are not Uploading files, just use the method="POST"

Am I proceeding with coding an edit and delete feature correctly in php/mysql, phpMyAdmin

I am working on adding a edit and delete feature to my basic blog app. I am struggling with having the my edit.php code and delete.php code process correctly.
When a person clicks on the delete or edit button the code in the correlating php file does not process.
Main PHP file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="container">
<h1>Lay Down Your Thoughts</h1>
<div id="boxtop"></div>
<div id="content">
<!-- form to leave a message -->
<form action="<?php $self ?>" method="post">
<h2>Post your thought!</h2>
<div class="fname"><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div>
<div class="femail"><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div>
<label for="message"><p>Message:</p></label>
<textarea name="post" rows="5" cols="40"></textarea>
<input name="send" type="hidden" />
<p><input type="submit" value="send" /></p>
</form>
<?php
$self = $_SERVER['PHP_SELF']; //the $self variable equals this file
$ipaddress = ("$_SERVER[REMOTE_ADDR]"); //the $ipaddress var equals users IP
include ('db.php');
// checks the POST to see if something has been submitted
if(isset($_POST['send']))
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['post'])) {
echo('<p class="error">You did not fill in a required field.</p>');
} else {
// if there are no empty fields, insert into the database:
//validate through htmlspecialchars()
// eliminates the user from submitting harmful html
// also runs through mysql_real_escape_string()
// stops users sending SQL code to infiltrate the db
$name = htmlspecialchars(mysql_real_escape_string($_POST['name']));
$email = htmlspecialchars(mysql_real_escape_string($_POST['email']));
$post = htmlspecialchars(mysql_real_escape_string($_POST['post']));
// this is our SQL string to insert shouts into db
$sql = "INSERT INTO messages SET name='$name', email='$email', post='$post', ipaddress='$ipaddress';";
// run the SQL string
// if it succeeds, display message
if (#mysql_query($sql)) {
echo('<p class="success">message has been posted</p>');
} else {
// if error, send message
echo('<p class="error">There was an unexpected error when posting your message.</p>');
}
}
// display 8 latest messages
$query = "SELECT * FROM messages ORDER BY `id` DESC LIMIT 8;";
// run query if it fails display fail
$result = #mysql_query("$query") or die('<p class="error">There was an unexpected error collecting messages.</p>');
?><ul><?
// display the rows from the post
while ($row = mysql_fetch_array($result)) {
$ename = stripslashes($row['name']);
$eemail = stripslashes($row['email']);
$epost = stripslashes($row['post']);
// gravatar image
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo('<li><div class="meta"><img src="'.$grav_url.'" alt="Gravatar" /><p>'.$ename.'</p></div><div class="message"><p>'.$epost.'</p></div></li>');
echo ('<form action="messageME_final_delete.php" method="post"><input name="delete" type="hidden" /> <p><input type="submit" value="delete" /></p></form>');
echo('<form action="messageME_final_update.php" method="post"><input name="edit" type="hidden" /> <p><input type="submit" value="edit" /></p></form>');
}
?></ul><?
?>
</div><!--/content-->
<div id="boxbot"></div>
</div><!--/container-->
</body>
</html>
Here is the Edit php file:
<form action="messageME_final_update.php" method="post">
<h2>Edit this Thought!</h2>
<div class="fname"><label for="name"><p>Name:</p></label><input name="name" type="text" cols="20" /></div>
<div class="femail"><label for="email"><p>Email:</p></label><input name="email" type="text" cols="20" /></div>
<label for="message"><p>Message:</p></label>
<textarea name="post" rows="5" cols="40"></textarea>
<input name="send" type="hidden" />
<p><input type="submit" value="send" /></p>
</form>
<?
include ('db.php');
$query="UPDATE messages SET name='name', email='email', post='post' WHERE id='ID'";
mysql_query($query);
echo "Record Updated";
mysql_close();
?>
finally here is the delete php code:
<?php
include ('db.php');
$sql = "DELETE FROM `messages` WHERE `ID` =" ." mysql_real_escape_string ( $_GET['ID'] )";
mysql_select_db ( $database, $connect );
if ( #mysql_query ( $sql ) )
{
echo 'Article ID = ' . $_POST['ID'];
echo ' was deleted successfully';
}
else {
die ( mysql_error () );
}
?>
Your update page has no code related to identifying what post the user wants to edit at all. It just presents a new form and tries to update a row with an ID of the string 'ID'.
Your delete page tries to access both $_GET['ID'] and $_POST['ID'], which won't ever both be set since an HTTP request is always of a single method (GET, or POST, or HEAD, etc). You also fail to concatenate the string with a function correctly, instead sending the literal text "mysql_real_escape_string(..." as part of the query, which will not run.
$sql = "DELETE FROM messages WHERE ID = " . (int)$_POST['ID'];
...is closer to what you want, except that your form on the post list does not contain an element named ID. You should create one, and populate it with the ID of the post that row corresponds to.
<input type="hidden" name="ID" value="<?php echo $row['ID']; ?>" />
Do the same for the form pointing to the edit page, and use $_POST['ID'] to look up the post and populate the form fields for editing.
Suggested reading, which will walk you through building all aspects of a CMS in PHP/MySQL:
http://www.amazon.com/Build-Database-Driven-Using-MySQL/dp/0980576814/ref=dp_ob_title_bk

Categories