MySQL Database/PHP - Generate 100 contacts from a script - php

Well I have most of the code working now. The point of the application is to store information from a contact form to a text file. So basically the point of the application is to take in information inputted by the user, store the information in a text file and allow the user to go back to the homepage.
It doesn't necessarily have to be a script to generate the contacts, it can be PHP, Bash, Script, HTML, etc. I just don't know how to do it!
Here is the code I have so far, I just need help with randomly generating the 100 contacts without manually inputting them, if I could get some input that would be appreciated :)
HTML CODE:
<form action="Registered.php" method="post">
<p>
<label>First Name:</label>
<input name="fName" type="text">
</p>
<p>
<label>Last Name:</label>
<input name="lName" type="text">
</p>
<p>
<label>Address:</label>
<input name="address" type="text">
</p>
<p>
<label>State:</label>
<select name="statedropdown">
<option value="Al"> Al </option>
<option value="AK"> AK </option>
<option value="AS">AS</option>
<option value="AR">AR</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="CT">CT</option>
<option value="DE">DE</option>
<option value="DC">DC</option>
<option value="FL">FL</option>
<option value="GA">GA</option>
<option value="HI">HI</option>
<option value="ID">ID</option>
<option value="IL">IL</option>
<option value="IN">IN</option>
<option value="IA">IA</option>
<option value="KS">KS</option>
<option value="KY">KY</option>
<option value="LA">LA</option>
<option value="ME">ME</option>
<option value="MD">MD</option>
<option value="MA">MA</option>
<option value="MI">MI</option>
<option value="MN">MN</option>
<option value="MS">MS</option>
<option value="MO">MO</option>
<option value="MT">MT</option>
<option value="NE">NE</option>
<option value="NV">NV</option>
<option value="NH">NH</option>
<option value="NJ">NJ</option>
<option value="NM">NM</option>
<option value="NY">NY</option>
<option value="NC">NC</option>
<option value="ND">ND</option>
<option value="OH">OH</option>
<option value="OK">OK</option>
<option value="OR">OR</option>
<option value="PA">PA</option>
<option value="RI">RI</option>
<option value="SC">SC</option>
<option value="SD">SD</option>
<option value="TN">TN</option>
<option value="UT">UT</option>
<option value="VT">VT</option>
<option value="VA">VA</option>
<option value="WA">WA</option>
<option value="WV">WV</option>
<option value="WI">WI</option>
<option value="WY">WY</option>
</select>
</p>
<p>
<label>ZIP Code:</label>
<input name="zip" required="required" placeholder="12345" type="text">
</p>
<p>
<label>Email:</label>
<input name="email" required="required" placeholder="fake#email.com" type="email">
</p>
<p>
<label>Phone Number:</label>
<input name="phone" required="required" placeholder="912-555-1234" type="text">
</p>
<p>
<input value="Submit" type="submit">
<input type="reset" value="Reset">
</p>
<p>
<td align="center"> View contacts in database </td>
</p>
<p>
<td align="center"> View contacts in file </td>
</p>
</body>
</html>
PHP CODE:
<html>
<head>
<title> Thank You </title>
</head>
<body>
<?php
$username="tp2283";
$password="tootandnut";
$database="tp2283";
#declare variables
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address = $_POST['address'];
$statedropdown = $_POST['statedropdown'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$DOCUMENT_ROOT = $SERVER['DOCUMENT_ROOT'];
mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
//$query = "SELECT * FROM contacts";
//$result = mysql_query($query);
//$num = mysql_num_rows($result);
$sql = mysql_query("SELECT * FROM contacts");
$file = "FormData.txt";
$fh = fopen($file, 'a') or die("can't open file");
while($row = mysql_fetch_array($sql)){
$username = $row['user'];
$password = $row['pass'];
$accounts = "$username:$password\n";
fwrite($fh, $accounts);
}
mysql_close();
fclose($fh);
?>
<h1 align = "center"> Thanks for Registering! </h1> <br /><br />
<p align = "center"> Your information is: </p>
<table align = "center">
<tr>
<td> First Name: </td>
<td> &nbsp </td>
<td> <?php echo $fName ?> </td>
</tr>
<tr>
<td> Last Name: </td>
<td> &nbsp </td>
<td> <?php echo $lName ?> </td>
</tr>
<tr>
<td> Address: </td>
<td> &nbsp </td>
<td> <?php echo $address ?> </td>
</tr>
<tr>
<td> State: </td>
<td> &nbsp </td>
<td> <?php echo $statedropdown ?> </td>
</tr>
<tr>
<td> Zip: </td>
<td> &nbsp </td>
<td> <?php echo $zip ?> </td>
</tr>
<tr>
<td> Telephone: </td>
<td> &nbsp </td>
<td> <?php echo $phone ?> </td>
</tr>
<tr>
<td> E-mail: </td>
<td> &nbsp </td>
<td> <?php echo $email ?> </td>
</tr>
</table>
<?php
$outputstring =
"First Name: $fName \n
Last Name: $lName \n
Address: $address \n
State: $statedropdown \n
Zip: $zip \n
Telephone: $phone \n
Email: $email \n
-----------------------\n";
file_put_contents("FormData.txt", $outputstring, FILE_APPEND | LOCK_EX);
?>
<p align="center"> Return to Main Page </p>
<p align="center"> View Contacts in Database </p>
</body>
</html>

Sooo... I know there's already an answer, but I decided to have a little fun with this.
My approach uses cURL and PHP and posts to the form via HTTP. This way, you can test that your PHP code works as well, beyond just testing the SQL schema. I also wanted to get kind-of real-world data. This will open and close a curl session every time (the same session is not reused). Anyways, like I said, just for fun:
<?php
$numPosts = 100;
$sleep = 0.1; // seconds
$postUrl = 'http://web-students.armstrong.edu/~tp2283/Registered.php';
$firstNames = array(
'Bill','William','Joe','Bob','David','Jerome','Shane','Matt','Michael','Andrew',
'Sally','Sue','Courtney','Olya','Kristin','Theresa','Cheri','Melony','Alex','Cindy'
);
$lastNames = array(
'Smith','Dobson','Johnson','Zammit','Brown','Jones','Miller','Garcia','Wilson','Martinez',
'Anderson','Taylor','Thomas','Moore','Martin','Jackson','Lopez','Lee','Harris','Clark'
);
$streets = array(
'Central Ave','Broadway','1st St','2nd St','3rd St','Washington St',
'Jefferson Ave','Woodcreek Blvd','Pines Dr','Big Cr','Tennis Ct'
);
$stateList = array(
'AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA','KS','KY',
'LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH',
'OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'
);
$domains = array(
'yahoo.com','mail.com','gmail.com','example.net','host.org',
'stuff.im','aol.com','hostmail.com','msn.com'
);
for ( $i = 0; $i < $numPosts; $i++ ) {
$data = array(
'fName' => generateFirst(),
'lName' => generateLast(),
'address' => generateStreet(),
'statedropdown' => generateState(),
'zip' => generateZip(),
'email' => generateEmail(),
'phone' => generatePhone()
);
$result = postData($postUrl,$data);
var_dump($result);
usleep($sleep/1000000);
}
function postData($url,$data) {
$ch = curl_init();
$opts = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_URL => $url
);
foreach ( $opts as $key => $value ) {
curl_setopt($ch,$key,$value);
}
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function generateFirst() {
global $firstNames;
return $firstNames[array_rand($firstNames)];
}
function generateLast() {
global $lastNames;
return $lastNames[array_rand($lastNames)];
}
function generateStreet() {
global $streets;
$houseNumber = mt_rand(1,3000);
$street = $streets[array_rand($streets)];
return $houseNumber.' '.$street;
}
function generateState() {
global $stateList;
return $stateList[array_rand($stateList)];
}
function generateZip() {
return str_pad(mt_rand(0,99999),5,'0',STR_PAD_LEFT);
}
function generateEmail() {
global $domains;
$randomCharacters = md5(mt_rand());
$firstIndex = mt_rand(3,7); // length
$user = substr($randomCharacters,0,$firstIndex);
$domain = $domains[array_rand($domains)];
return $user.'#'.$domain;
}
function generatePhone() {
$areacode = mt_rand(100,999);
$first3 = mt_rand(100,999);
$last4 = mt_rand(1000,9999);
return $areacode.'-'.$first3.'-'.$last4;
}
?>
It is split up into functions, so adding random variance with regard to input format should be pretty easy to do, if you want to also consider server-side form validation.
I also added a sleep time (in seconds, but using usleep which is in microseconds) so as not to overload the server.... I suppose if you distributed this, you could also performance test.
Usage (tailored to OP):
Create a new/blank file called populate.php
Copy the code contents in this post (including the <?php and ?> tags) and paste into the populate.php file
Change the value of $numPosts (currently 100) to 2 for the purpose of testing: $numPosts = 2;
If you a remotely accessing the server web-students.armstrong.edu (via FTP, SCP, a file management system in your browser, etc.) upload the populate.php file to your directory (~tp2283). Depending on the software and configuration this directory could be hidden in which case just upload to the top-most directory.
In a browser, navigate to http://web-students.armstrong.edu/~tp2283/populate.php
Wait for the script to finish...
Notice the output: it should be HTML markup from the Registered.php page twice (one time for each of the $numPosts
Once successful, update $numPosts to 100 (edit locally, then reupload and overwrite, if necessary)
Refresh the http://web-students.armstrong.edu/~tp2283/populate.php page in your browser. You should now have the HTML from Registered.php x100.
Check your database, there should be 102 (2 + 100) new entries.
This may not work if cURL is not enabled/installed: how to check if curl is enabled or disabled. In which case a different method using file_get_contents will be required, in which case it will only work if allow_url_fopen is enabled.
If you are running PHP locally, you can always change/update these features to allow the functionality. These specifics are outside the scope of this question.

Assuming you are asking for 100 fake contacts to test with...
A basic loop would do it
<?php
for($i = 0; $i < 100; $i ++)
{
mysql_query("INSERT INTO `contacts` (`first_name`, `email`, `etc`) VALUES ('someone ".rand(0,999)."','someone".rand(0,999)."#test.com','etc')");
}
?>
Obviously this relies on an open connection and your actual fields plugged in. No need to bother with escaping anything since this is just script generated test data, right?
Obligatory announcement: mysql_ functions are deprecated. Switch to mysqli or PDO. There are plenty of resources available with just simple google searches like "mysqli_connect" etc.
If this is not what you needed, please update your question.

Please use PHP Faker which generates the fake data for you. You can find the this PHP Library # https://github.com/fzaninotto/Faker. The link guides you how to install and use the more advanced and wide range of features as per your needs.
With the help of this library you can generate as many as data with no time.
The following is the snippet of its usage -
<?php
require_once 'vendor/autoload.php';
$faker = Faker\Factory::create();
$person = new Faker\Provider\en_US\Person($faker);
$address = new Faker\Provider\en_US\Address($faker);
/* You can loop as many times the data you want to generate */
foreach(range(1,10) as $i){
echo $person->titleMale(),'.',$person->name('male'),'<br/>';
}

Related

How to submit multiple rows from an html form into a db table?

I want to insert all values with just a function and I don't want to rewrite the same code many times but I have the problem that this function just inserts the first values (I checked the input name and it's set correctly).
$name = htmlspecialchars($_POST["name"]);
$prix = htmlspecialchars($_POST["prixing"]);
$prixn = htmlspecialchars($_POST["quantite"]);
$uniteing = $_POST['unite'];
$date = date('Y-m-d');
<?php
$servername = "localhost";
$username = "root";
$password = "test";
$dbname = "test";
// Create connection $conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } //
variable $date = date('Y-m-d');
$name = htmlspecialchars($_POST["name"]);
$name1 = htmlspecialchars($_POST["name1"]);
$prix = htmlspecialchars($_POST["prixing"]);
$prix1 = htmlspecialchars($_POST["prixing1"]);
$prixn = htmlspecialchars($_POST["quantite"]);
$prixn1 = htmlspecialchars($_POST["quantite1"]);
$uniteing = $_POST['unite'];
$uniteing1 = $_POST['unite1'];
$name2 = htmlspecialchars($_POST["name2"]);
$name3 = htmlspecialchars($_POST["name3"]);
$prix2 = htmlspecialchars($_POST["prixing2"]);
$prix3 = htmlspecialchars($_POST["prixing3"]);
$prixn2 = htmlspecialchars($_POST["quantite2"]);
$prixn3 = htmlspecialchars($_POST["quantite3"]);
$uniteing2= $_POST['unite2'];
$uniteing3 = $_POST['unite3'];
$name4 = htmlspecialchars($_POST["name4"]);
$name5 = htmlspecialchars($_POST["name5"]);
$prix4 = htmlspecialchars($_POST["prixing4"]);
$prix5 = htmlspecialchars($_POST["prixing5"]);
$prixn4 = htmlspecialchars($_POST["quantite4"]);
$prixn5 = htmlspecialchars($_POST["quantite5"]);
$uniteing4 = $_POST['unite4'];
$uniteing5 = $_POST['unite5'];
$name6 = htmlspecialchars($_POST["name6"]);
$name7 = htmlspecialchars($_POST["name7"]);
$prix6 = htmlspecialchars($_POST["prixing6"]);
$prix7 = htmlspecialchars($_POST["prixing7"]);
$prixn6 = htmlspecialchars($_POST["quantite6"]);
$prixn7 = htmlspecialchars($_POST["quantite7"]);
$uniteing6 = $_POST['unite6'];
$uniteing7 = $_POST['unite7'];
$name8 = htmlspecialchars($_POST["name8"]);
$name9 = htmlspecialchars($_POST["name9"]);
$prix8 = htmlspecialchars($_POST["prixing8"]);
$prix9 = htmlspecialchars($_POST["prixing9"]);
$prixn8 = htmlspecialchars($_POST["quantite8"]);
$prixn9 = htmlspecialchars($_POST["quantite9"]);
$uniteing8 = $_POST['unite8'];
$uniteing9 = $_POST['unite9'];
$name10 = htmlspecialchars($_POST["name10"]);
$prix10 = htmlspecialchars($_POST["prixing10"]);
$prixn10 = htmlspecialchars($_POST["quantite10"]);
$uniteing10 = $_POST['unite10'];
//end variable 2
function insert($namex, $prixx,$prixnx, $datex, $uniteingx,$conn)
{
$sql = "INSERT INTO ingredient
VALUES ('$namex','$prixx','$prixnx','$datex','$uniteingx')";
$res = mysqli_query($conn, $sql);
if ($res) {
echo "New record created successfully";
mysqli_error($conn);
} else {
echo "_error_: " . $sql . "<br>" . mysqli_error($conn);
}
}
insert($name, $prix,$prixn, $date, $uniteing,$conn);
insert($name1, $prix1,$prixn1, $date1, $uniteing1,$conn);
insert($name2, $prix2,$prixn2, $date2, $uniteing2,$conn);
insert($name3, $prix3,$prixn3, $date3, $uniteing3,$conn);
insert($name4, $prix4,$prixn4, $date4, $uniteing4,$conn);
insert($name5, $prix5,$prixn5, $date5, $uniteing5,$conn);
insert($name6, $prix6,$prixn6, $date6, $uniteing6,$conn);
insert($name7, $prix7,$prixn7, $date7, $uniteing7,$conn);
insert($name8, $prix8,$prixn8, $date8, $uniteing8,$conn);
insert($name9, $prix9,$prixn9, $date9, $uniteing9,$conn);
insert($name10, $prix10,$prixn10, $date10, $uniteing10,$conn);
header('Location: ../index.html'); ?>
Here is my form:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
</head>
<body>
<form action="php/insert-multi-ing.php" method="POST">
<table>
<tr>
<th>Nom Ingrédient</th>
<th>Prix Ingrédient</th>
<th>Quantite Ingrédient</th>
<th>Unite</th>
</tr>
<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="prixing"></td>
<td><input type="text" name="quantite"></td>
<td>
<select name="unite" id="unites">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name1"></td>
<td><input type="text" name="prixing1"></td>
<td><input type="text" name="quantite1"></td>
<td>
<select name="unite1" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name2"></td>
<td><input type="text" name="prixing2"></td>
<td><input type="text" name="quantite2"></td>
<td>
<select name="unite2" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name3"></td>
<td><input type="text" name="prixing3"></td>
<td><input type="text" name="quantite3"></td>
<td>
<select name="unite3" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name4"></td>
<td><input type="text" name="prixing4"></td>
<td><input type="text" name="quantite4"></td>
<td>
<select name="unite4" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name5"></td>
<td><input type="text" name="prixing5"></td>
<td><input type="text" name="quantite5"></td>
<td>
<select name="unite5" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name6"></td>
<td><input type="text" name="prixing6"></td>
<td><input type="text" name="quantite6"></td>
<td>
<select name="unite6" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name7"></td>
<td><input type="text" name="prixing7"></td>
<td><input type="text" name="quantite7"></td>
<td>
<select name="unite7" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name8"></td>
<td><input type="text" name="prixing8"></td>
<td><input type="text" name="quantite8"></td>
<td>
<select name="unite8" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name9"></td>
<td><input type="text" name="prixing9"></td>
<td><input type="text" name="quantite9"></td>
<td>
<select name="unite9" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
<tr>
<td><input type="text" name="name10"></td>
<td><input type="text" name="prixing10"></td>
<td><input type="text" name="quantite10"></td>
<td>
<select name="unite10" id="">
<option value="kg">kg</option>
<option value="G">G</option>
<option value="L">L</option>
<option value="ml">Ml</option>
<option value="cl">Cl</option>
<option value="Piece">Piece</option>
</select>
</td>
</tr>
</table>
<button>Ajouter ingrédient</button>
</form>
</body>
</html>
You shouldn't repeat your form fields as a list name0, name1 .. name99 instead you need to send them as an array like: data[0][name] .. data[99][name]
Also better generate your HTML with PHP for not violating DRY rule, you'll apreciate that when will need to edit the form with reperating fields in the future:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
</head>
<body>
<form action="php/insert-multi-ing.php" method="POST">
<table>
<tr>
<th>Nom Ingrédient</th>
<th>Prix</th>
<th>Prix Ingrédient</th>
<th>Quantite Ingrédient</th>
<th>Unite</th>
</tr>
<?php
for ($i = 0; $i < 10; $i++) {
echo "
<tr>
<td><input type='text' name='data[{$i}][name]'></td>
<td><input type='text' name='data[{$i}][prix]'></td>
<td><input type='text' name='data[{$i}][prixn]'></td>
<td><input type='text' name='data[{$i}][quantite]'></td>
<td>
<select name='data[{$i}][unite]' id='unite_{$i}'>
<option>kg</option>
<option>G</option>
<option>L</option>
<option>Ml</option>
<option>Cl</option>
<option>Piece</option>
</select>
</td>
</tr>
";
}
?>
</table>
<button>Ajouter ingrédient</button>
</form>
</body>
</html>
Here's the sample for accessing it as a multidimensional array in PHP and inserting to DB with prepared statement. Keep in mind that I use PDO instead of mysqli here which I advice you to:
<?php
$data = $_POST['data'] ?? null;
if (!is_null($data)) {
$pdo = new PDO("mysql:host=127.0.0.1;dbname=test;charset=utf8", "yourusername", "yourpassword");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("
INSERT
INTO ingredient (name, prix, prixn, unite, quantite, date)
VALUES (:name, :prix, :prixn, :unite, :quantite, NOW())
");
$stmt->bindParam('name', $name);
$stmt->bindParam('prix', $prix);
$stmt->bindParam('prixn', $prixn);
$stmt->bindParam('quantite', $quantite);
$stmt->bindParam('unite', $unite);
foreach ($data as $item) {
// Adds some data validation to make sure you won't save million empty rows,
// also add custom validation for other fields (if any)
$name = checkValue($item['name']);
$prix = checkValue($item['prix']);
$prixn = checkValue($item['prixn']);
$quantite = floatval($item['quantite']);
$unite = checkValue($item['unite']);
if (!is_null($name) && !is_null($prix) && !is_null($prixn) && $quantite > 0) {
$stmt->execute();
}
}
}
/**
* check if the string value is not null and not empty
*
* #param $value
*
* #return string|null
*/
function checkValue($value)
{
return (is_null($value) || trim($value) == '') ? null : $value;
}
Note your code is messy and it's quite possible that I used wrong column names or field names in form, just fix it. In general that works.
Your code is subject to SQL injection. It's better to use parameterized queries. They take care of quoting, fixing data that might include SQL injection, etc.
They also execute faster when executing the same statement repeatedly.
Note: Code not tested, may require some syntax checking and other corrections
<?php
// Create PDO connection
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Create list of base column names
$colList = array(
'name',
'prix',
'prixn',
'uniteing'
);
// Create array to hold column values from $_POST
$val = Array(null,null,null,null);
// Prepare SQL statement with place holders, be sure to explicitly list the table column names. Substitute the actual column names for those below.
$stmt = $dbh->prepare("INSERT INTO ingredient (`namex`,`prixx`,`prixnx`,`uniteingx`) VALUES (:namex,:prixx,:prixnx,:uniteingx)");
// Bind each array value to a place holder
$stmt->bindParam(':namex',$val[1]);
$stmt->bindParam(':prixx',$val[2]);
$stmt->bindParam(':prinx',$val[3]);
$stmt->bindParam(':uniteingx',$val[4]);
// Step through the column name suffix values from the form
for($i=0;$i<=10;$i++) {
// Special case for the first (0) value (i.e. no suffix)
$suffix = $i > 0 ? $i : '';
// Load the 5 column values from the post variables into the $val array
foreach($colList as $colNum, $colName) {
$val[$colNum] = $_POST[$colName . $suffix];
}
// Execute the SQL statement above with the current values in $val
$stmt->execute();
}
?>
To begin, craft your html form so that it is fit for purpose and doesn't violate html document standards.
You should be generating the rows of input fields inside of a loop.
You should declare the name attributes of each field using array syntax so that row data is submitted in grouped subarrays -- this will make subsequent processes much easier. By simply trailing the field name with [], you can avoid cluttering your file with unnecessary php syntax.
You must not have duplicated id attributes in a single document. You could append a counter to the end of the id strings, but there is a high probability that you don't need the id declarations at all -- I'll omit them.
There is zero benefit in duplicating an <option>'s text as its value value. Simply omit that attribute declaration as well.
Use a whitelist of measurement units so that you don't need to write out each <option> tag over and over. This will improve the maintainability of your script.
For improved UX, use field attributes such as: title, placeholder, pattern, minlength, maxlength, required, etc. as well as potentially type="number" to guide the users about how to form valid entries. These simple touches will not only help to prevent user frustration, they will spare your application from making fruitless trips to the database and/or only storing partial submissions.
<table>
<tr>
<th>Nom Ingrédient</th>
<th>Prix Ingrédient</th>
<th>Quantite Ingrédient</th>
<th>Unite</th>
</tr>
<?php
$numberOfRows = 10;
$units = ['kg', 'G', 'L', 'ml', 'Cl', 'Piece'];
for ($i = 0; $i < $numberOfRows; ++$i) {
?>
<tr>
<td><input type="text" name="name[]"></td>
<td><input type="text" name="price[]"></td>
<td><input type="text" name="quantity[]"></td>
<td>
<select name="unit[]">
<option><?php echo implode('</option><option>', $units); ?></option>
</select>
</td>
</tr>
<?php
}
?>
</table>
As for your database table setup, here are some tips:
Avoid vague column naming like date. Rename the column as insert_date or created_on or something similar so that the value is more informative to future readers of your scripts/project.
Modify the schema of your ingredients table to set the DEFAULT value of insert_date as CURRENT_DATE. In doing so, you will never need to write this column into your INSERT queries -- the database will use the current date automatically when you do not pass a value for that column.
If this table doesn't have an AUTOINCREMENTing id column, you should add one and make it the PRIMARY KEY. This is a very basic technique to improve future interactions with the table and will eliminate possible confusion when you find that someone has submitted a duplicate name into the table.
As for processing your submitted data, there are only a few simple steps to follow:
Iterate the $_POST array and isolate each row of data to be inserted into the database.
Once isolated, you need to validate and optionally sanitize each row BEFORE executing the query so that you never store "bad data" in your table.
You are using mysqli and that is just fine -- you don't need to switch to pdo to write secure/stable code.
4 You will only need to generate a prepared statement once and bind variables to placeholders once. Only the (conditional) execution of the statement needs to be inside the loop. (some other examples: 1, 2, 3)
I will recommend, however, that you switch from mysqli's procedural syntax to its object-oriented syntax. It is more concise and I find it simpler to read.
// create a mysqli connection object e.g. $mysqli = new mysqli(...$credentials);
$sql = "INSERT INTO ingredients (`id`, `name`, `price`, `quantity`, `unit`)
VALUES (NULL, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('sdds', $name, $price, $quantity, $unit); // Assumes price and quantity are float values
$failures = [];
$affectedRows = 0;
$units = ['kg', 'G', 'L', 'ml', 'Cl', 'Piece'];
foreach ($_POST['name'] as $index => $name) {
// adjust the validation/sanitization processes as you wish
$name = trim($name);
$price = trim($_POST['price'][$index]);
$quantity = trim($_POST['quantity'][$index]);
$unit = trim($_POST['unit'][$index]);
$rowNo = $index + 1;
if (!strlen($name) || !strlen($price) || !strlen($quantity) || !in_array($unit, $units)) {
$failures[] = "Missing/Invalid value on row $rowNo";
} elseif (!$stmt->execute());
$failures[] = "A syntax error has occurred"; // check your error logs
} else {
++$affectedRows;
}
}
echo "Affected Rows: $affectedRows";
if ($failures) {
echo "<ul><li>" , implode('</li><li>', $failures) , "</li></ul>";
}
Some overall advice:
avoid mixing your French and your English. If you are going to use French variable names, then use ALL French variables. That said, I have read advice from native English speakers and English-as-a-Second-Language developers who state that you should always use ALL English in your code -- this is a a debate, I will not weigh in on this right now.
When to use htmlspecialchars() function? You will notice that at no point did I call this function in my answer. This is because at no point are we printing any of the user's input to screen. Validate? Yes. Sanitize? Sure. HTML Encode? Nope; not here, not now.
If these rows of ingredients are meant to relate to specific recipe table rows, then you will need to establish a FOREIGN KEY relationship. The recipes table will need an id column and the ingredients table will need a column like recipe_id which stores that respective recipe id. Assuming your html form will already know which recipe is being referred to, you should include a <input type="hidden" name="recipe" value="<?php echo $recipeId; ?>"> field on the line under your <form> tag. Then when saving data, you must save the $_POST['recipe'] value with each ingredients row. Then you are making better use a of "relational database".

How do i make my edit php auto select the dropdown menu option that is in the database

I can't get my dropdown menu (in edit.php) to select the option that i choose. I can also not edit the value through text form, it just gets submited but nothing happends (I can edit other values with it)
Ive already tried with no luck
<?php
if($row["rank"]=='Unranked')
{
echo "Unranked";
}
?>
This is my option code
<select id="rank" name="rank">
<option value = "No Selected">Select a rank</option>
<option value = "Unranked">Unranked</option>
<option value = "Silver 1">Silver 1</option>
<option value = "Silver 2">Silver 2</option>
<option value = "Silver 3">Silver 3</option>
<option value = "Silver 4">Silver 4</option>
<option value = "Silver Elite">Silver Elite</option>
<option value = "Silver Elite Master">Silver Elite Master</option>
<option value = "Gold Nova 1">Gold Nova 1</option>
<option value = "Gold Nova 2">Gold Nova 2</option>
<option value = "Gold Nova 3">Gold Nova 3</option>
<option value = "Gold Nova master">Gold Nova master</option>
<option value = "Master Guardian 1">Master Guardian 1</option>
<option value = "Master Guardian 2">Master Guardian 2</option>
<option value = "Master Guardian Elite">Master Guardian Elite</option>
<option value = "Distinguished Master Guardian">Distinguished Master Guardian</option>
<option value = "Legendary Eagle">Legendary Eagle</option>
<option value = "Legendary Eagle Master">Legendary Eagle Master</option>
<option value = "Supreme">Supreme Master First Class</option>
<option value = "Global Elite">Global Elite</option>
</select>
I would like it to auto select the selected option and to acctually work
EDIT 54523(im new to this site sigh):
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$Id = $_POST['Id'];
$username=$_POST['username'];
$password=$_POST['password'];
$friendcode=$_POST['friendcode'];
$rank = $_POST['rank'];
$lvl = $_POST['lvl'];
// checking empty fields
if(empty($username) || empty($password) || empty($friendcode) || empty($rank) || empty($lvl)) {
if(empty($username)) {
echo "<font color='red'>Please enter a username</font><br/>";
}
if(empty($password)) {
echo "<font color='red'>Please enter a password</font><br/>";
}
if(empty($friendcode)) {
echo "<font color='red'>Please enter a friendcode</font><br/>";
}
if(empty($rank)) {
echo "<font color='red'>Please select a rank</font><br/>";
}
if(empty($lvl)) {
echo "<font color='red'>Please select a level</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE legit SET username='$username',password='$password',friendcode='$friendcode' WHERE Id=$Id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$Id = $_GET['Id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM legit WHERE Id=$Id");
while($res = mysqli_fetch_array($result))
{
$username= $res['username'];
$password= $res['password'];
$friendcode= $res['friendcode'];
$rank= $res['rank'];
$lvl= $res['lvl'];
}
?>
<html>
<head>
<title>Edit account ID <?php echo $Id;?></title>
</head>
<body>
<div align="center">
Go back to account list
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Username</td>
<td><input type="text" name="username" value="<?php echo $username;?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" value="<?php echo $password;?>"></td>
</tr>
<tr>
<td>Friendcode</td>
<td><input type="text" name="friendcode" value="<?php echo $friendcode;?>"></td>
</tr>
<tr>
<td>Rank</td>
<td>
<select id="rank" name="rank">
<option value = "No Selected">Select a rank</option>
<option value = "Unranked">Unranked</option>
<option value = "Silver 1">Silver 1</option>
<option value = "Silver 2">Silver 2</option>
<option value = "Silver 3">Silver 3</option>
<option value = "Silver 4">Silver 4</option>
<option value = "Silver Elite">Silver Elite</option>
<option value = "Silver Elite Master">Silver Elite Master</option>
<option value = "Gold Nova 1">Gold Nova 1</option>
<option value = "Gold Nova 2">Gold Nova 2</option>
<option value = "Gold Nova 3">Gold Nova 3</option>
<option value = "Gold Nova master">Gold Nova master</option>
<option value = "Master Guardian 1">Master Guardian 1</option>
<option value = "Master Guardian 2">Master Guardian 2</option>
<option value = "Master Guardian Elite">Master Guardian Elite</option>
<option value = "Distinguished Master Guardian">Distinguished Master Guardian</option>
<option value = "Legendary Eagle">Legendary Eagle</option>
<option value = "Legendary Eagle Master">Legendary Eagle Master</option>
<option value = "Supreme">Supreme Master First Class</option>
<option value = "Global Elite">Global Elite</option>
</select>
</td>
</tr>
</tr>
<tr>
<td><input type="hidden" name="Id" value=<?php echo $_GET['Id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
The easiest way I can think of to do this would be to store your rankings in the database. Then, when the page loads, execute a SELECT query to pull the ranking options from the database. Next, loop through those results to build your drop down list checking to see if the current value matches the value selected. If it does, add selected to the <option></option> tag. For example:
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update'])) {
$Id = $_POST['Id'];
$username = $_POST['username'];
$password = $_POST['password'];
$friendcode = $_POST['friendcode'];
$rank = $_POST['rank'];
$lvl = $_POST['lvl'];
// checking empty fields
if (empty($username) || empty($password) || empty($friendcode) || empty($rank) || empty($lvl)) {
if (empty($username)) {
echo "<font color='red'>Please enter a username</font><br/>";
}
if (empty($password)) {
echo "<font color='red'>Please enter a password</font><br/>";
}
if (empty($friendcode)) {
echo "<font color='red'>Please enter a friendcode</font><br/>";
}
if (empty($rank)) {
echo "<font color='red'>Please select a rank</font><br/>";
}
if (empty($lvl)) {
echo "<font color='red'>Please select a level</font><br/>";
}
} else {
// updating the table
$result = mysqli_query($mysqli, "UPDATE legit SET username='$username',password='$password',friendcode='$friendcode' WHERE Id = $Id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
// getting id from url
$Id = $_GET['Id'];
// selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM legit WHERE Id = $Id");
while($res = mysqli_fetch_array($result)) {
$username = $res['username'];
$password = $res['password'];
$friendcode = $res['friendcode'];
$rank = $res['rank'];
$lvl = $res['lvl'];
}
?>
<html>
<head>
<title>Edit account ID <?php echo $Id;?></title>
</head>
<body>
<div align="center">
Go back to account list
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Username</td>
<td><input type="text" name="username" value="<?php echo $username;?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" value="<?php echo $password;?>"></td>
</tr>
<tr>
<td>Friendcode</td>
<td><input type="text" name="friendcode" value="<?php echo $friendcode;?>"></td>
</tr>
<tr>
<td>Rank</td>
<td>
<select id="rank" name="rank">
<?php
// select ranking options from database
$rankings = mysqli_query($mysqli, "SELECT * FROM rankings");
while($ranking = mysqli_fetch_array($rankings)) {
if ($ranking['id'] == $rank) {
echo "<option value=" . $ranking['id'] . " selected>" . $ranking['name'] . "</option>";
} else {
echo "<option value=" . $ranking['id'] . ">" . $ranking['name'] . "</option>";
}
}
?>
</select>
</td>
</tr>
</tr>
<tr>
<td><input type="hidden" name="Id" value=<?php echo $_GET['Id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
When adding selected, the four line IF statement could be swapped out for an inline IF statement, reducing the code. Also, when adding new rankings, you would just add them to the database table instead of having to modify your code. You want as much dynamically driven data as possible, if my opinion.
Also, stay consistent with your variables. Do not use cAmElCaSe mixed with all lowercase. Consistent see big when it comes to development and having clean code. That's the one big thing I stress to all of my developers.

PHP: How to carry over session variables between 3 pages?

So as of now, i can successfully get the results to move from page one to page two using post and get, but no matter what im doing it will not move the info to the 3rd page. Im trying to switch it over to sessions after reading its made exactly for this but for some reason im doing something wrong and after hours of searching i cant for the life of me figure out what it is. I've followed guides, followed videos, and other post related to the topic on this website. I have now come to the conclusion that it is just me and i need some assistance. Any help would be greatly appreciated.
Page 1 (Index Page | Input Your Variables):
<?php session_start();
$_GET['q'] = $q;
$_GET['s'] = $s;
?>
<form action="search.php" method="get">
<input name="q" maxlength="8" type="text" placeholder="License Plate" id="textbox" required />
<select name="s" id="s" required aria-required="true">
<option value="" disabled selected>CHOOSE STATE</option>
<option value="AL">ALABAMA</option>
<option value="AK">ALASKA</option>
<option value="AZ">ARIZONA</option>
<option value="AR">ARKANSAS</option>
<option value="CA">CALIFORNIA</option>
<option value="CO">COLORADO</option>
<option value="CT">CONNECTICUT</option>
etc...
</select>
<input type="submit" value="SEARCH" id="submitbtn"></form>
Page 2 (Search.php that will take you directly to page specified if its already been created):
<?php session_start();
$q = $_POST['q'];
$s = $_POST['s'];
?>
<?php
$dir = 'states';
$s = (isset($_GET['s']))? strtolower($_POST['s']) : '';
$q = (isset($_GET['q']))? strtoupper($_POST['q']) : '';
$res = opendir($dir);
while(false!== ($file = readdir($res))) {
if(strpos(strtoupper($file),$q)!== false &&!in_array($file)) {
echo "<a href='$dir/$s/$q.htm'>$file</a>";
}
}
closedir($res);
?>
<?php
echo $htmlHeader;
while($stuff){
echo $stuff;
}
echo "<script>window.location =
'http://www.somesite.com/$dir/$s/$q.htm'</script>";
?>
Page 3 (404 page for catch all that are not in the system):
<?php session_start();
?>
<form action="" method="" name="FormChoice">
<input name="q" maxlength="8" type="text" value="<?php echo $_POST['q']; ?>" id="q" required>
<select name="s" id="s" required aria-required="true">
<option value="" disabled>CHOOSE STATE</option>
<option value="AL" <?php if($_POST['s'] == al) {echo ' selected="selected"';} ?>>ALABAMA</option>
<option value="AK" <?php if($_POST['s'] == ak) {echo ' selected="selected"';} ?>>ALASKA</option>
<option value="AZ" <?php if($_POST['s'] == az) {echo ' selected="selected"';} ?>>ARIZONA</option>
<option value="AR" <?php if($_POST['s'] == ar) {echo ' selected="selected"';} ?>>ARKANSAS</option>
<option value="CA" <?php if($_POST['s'] == ca) {echo ' selected="selected"';} ?>>CALIFORNIA</option>
<option value="CO" <?php if($_POST['s'] == co) {echo ' selected="selected"';} ?>>COLORADO</option>
<option value="CT" <?php if($_POST['s'] == ct) {echo ' selected="selected"';} ?>>CONNECTICUT</option>
</select>
<input type="submit" id="submitbtn2" value="SEARCH" name="submit" OnClick="search()" />
<span id="or">OR</span>
<input type="submit" id="addbtn" value="ADD" name="submit" OnClick="add()" />
</form>
page1
<?php
session_start();
// next 2 lines do NOTHING remove them
// as you have not yet loaded any values into $q and $s
//$_GET['q'] = $q;
//$_GET['s'] = $s;
?>
<form action="search.php" method="get">
<input name="q" maxlength="8" type="text" placeholder="License Plate" id="textbox" required />
<select name="s" id="s" required aria-required="true">
<option value="" disabled selected>CHOOSE STATE</option>
<option value="AL">ALABAMA</option>
<option value="AK">ALASKA</option>
<option value="AZ">ARIZONA</option>
<option value="AR">ARKANSAS</option>
<option value="CA">CALIFORNIA</option>
<option value="CO">COLORADO</option>
<option value="CT">CONNECTICUT</option>
etc...
</select>
<input type="submit" value="SEARCH" id="submitbtn"></form>
Page 2 - Search - receives data from previous form
- Contains lots of unecessary <?php...?>
- Previous form uses method="get" so data will arrive in the $_GET array not the $_POST array
<?php
session_start();
//$q = $_POST['q'];
//$s = $_POST['s'];
// But this is silly as you have not yet tested these values exist
// but you do that in the next lines
//$q = $_GET['q'];
//$s = $_GET['s'];
$dir = 'states';
$s = (isset($_GET['s']))? strtolower($_POST['s']) : '';
$q = (isset($_GET['q']))? strtoupper($_POST['q']) : '';
$res = opendir($dir);
// Now if you want to pass the values of `q` and `s` on to the next form
// they now need to be added to the session
$_SESSION['q'] = $q;
$_SESSION['s'] = $s;
while(false!== ($file = readdir($res))) {
if(strpos(strtoupper($file),$q)!== false &&!in_array($file)) {
echo "<a href='$dir/$s/$q.htm'>$file</a>";
}
}
closedir($res);
echo $htmlHeader;
while($stuff){
echo $stuff;
}
echo "<script>
window.location = 'http://www.somesite.com/$dir/$s/$q.htm';
</script>";
// added missing semi colon ^
?>
Page 3 (404 page for catch all that are not in the system):
Now the data will be available in the SESSION, when you get to this page.

Regarding PHP form

I am working on my project I want to store my multiple selected option value in the database but when I select more than one option at one time that time my only last selected values stored in DB please help my where am I am wrong?
Here is my Code:
<?php
require_once('contact_fun.php');
require_once('contact_banner_fun.php');
$obj = new contact_banner();
$crud = new contact_us();
$banner = $obj->get_data_banner();
if(!$banner){
echo "No Banner";
exit;}
$path = 'http://localhost/THE_VELVET_WALK/contact/';
$result = $crud->getData("SELECT * FROM tb_contactus");
foreach ($result as $res) {
$id = $res['id'];
$name = $res['name'];
$business = $res['business'];
$email = $res['email'];
$phone = $res['phone'];
$message = $res['message'];
$style = $res['style'];
}
if(isset($_POST['submit']))
{
$name = $crud->escape_string($_POST['name']);
$business = $crud->escape_string($_POST['business']);
$email = $crud->escape_string($_POST['email']);
$phone = $crud->escape_string($_POST['phone']);
$message = $crud->escape_string($_POST['message']);
$style = $crud->escape_string($_POST['style']);
$result = $crud->execute(" INSERT INTO tb_contactus(name, business, email,
phone, message, style, update_dt)VALUES ('$name','$business', '$email',
'$phone', '$message', '$style', now())");
}?>
<form action="" method="POST">
<input id="00N7F000001F2j6" name="name" maxlength="40" type="text"
class="materialize-input">
<input id="company" name="business" maxlength="40" type="text"
class="materialize-input">
<input id="email" name="email" maxlength="40" type="email"
class="materialize-input">
<input id="phone" name="phone" maxlength="40" type="text" maxlength="40"
class="materialize-input">
<select multiple id="00N7F000001F2kO" name="style" multiple="multiple" >
<option name="consulting" name="styling" value=""selected disabled>image
consulting</option>
<option value="1">styling</option>
<option value="2">hair & make-up</option>
<option value="3">designing clothes</option>
<option value="4">wedding makeover</option>
<option value="5">personal shopper</option>
<option value="6">corporate services</option>
</select>
</form>
you have to specify in the name of the select that it will be an array like :
<select multiple id="00N7F000001F2kO" name="style[]" multiple="multiple" >
<option value=""selected disabled>image consulting</option>
<option value="1">styling</option>
<option value="2">hair & make-up</option>
<option value="3">designing clothes</option>
<option value="4">wedding makeover</option>
<option value="5">personal shopper</option>
<option value="6">corporate services</option>
</select>
and then you can implode it if you want a string like this
implode(',',$_POST['style']);
EDIT :
change this
$style = $crud->escape_string($_POST['style']);
to
$style = $crud->escape_string(implode(',',$_POST['style']));
you need to use an array for multiple select options :
<select multiple id="00N7F000001F2kO" name="style[]" multiple="multiple" >
<option name="consulting" name="styling" value=""selected disabled>image
consulting</option>
<option value="1">styling</option>
<option value="2">hair & make-up</option>
<option value="3">designing clothes</option>
<option value="4">wedding makeover</option>
<option value="5">personal shopper</option>
<option value="6">corporate services</option>
</select>
this is how tou get the data into your database :
.php
if(isset($_POST['styling']) && !empty($_POST['styling'])){
$Col1_Array = $_POST['styling'];
print_r($Col1_Array);
foreach($Col1_Array as $selectValue){
//show selected
echo $selectValue."<br>";
}
}

radio buttons setting account type in mysqli

hey guys need to pick your brains, i currently have a form set up that uses 6 radio buttons which do 2 things.
a, is supposed to set my account field in mysqli which uses a enym field with the values of a,b,c ect
b, shows a div that includes my resgistration form showing the fields i need based on the account.
the problem i have faced is getting the the data into mysqli of which radio button is selected or "checked". all the other fileds in the form post into mysql fine its just getting the radio button to post its value.
ok php is as follows
<?php
$errorMsg = "";
// First we check to see if the form has been submitted
if (isset($_POST['firstname'])){
//Connect to the database through our include
include_once "connect_to_mysql.php";
// Filter the posted variables
$username = preg_replace("[^A-Za-z0-9]", "", $_POST['username']); // filter everything but numbers and letters
$firstname = preg_replace("[^A-Za-z]", "", $_POST['firstname']); // filter everything but letters
$surname = preg_replace("[^A-Za-z]", "", $_POST['surname']); // filter everything but letters
$accounttype = preg_replace("[^a-z]", "", $_POST['accounttype']); // filter everything but lowercase letters
$b_m = preg_replace('#[^0-9]#i', '', $_POST['birth_month']); // filter everything but numbers
$b_d = preg_replace('#[^0-9]#i', '', $_POST['birth_day']); // filter everything but numbers
$b_y = preg_replace('#[^0-9]#i', '', $_POST['birth_year']); // filter everything but numbers
$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
$pf = preg_replace("[^a-z]", "", $_POST['pf']);
$sa = preg_replace("[^a-z]", "", $_POST['sa']);
$ba = preg_replace("[^a-z]", "", $_POST['ba']);
$ve = preg_replace("[^a-z]", "", $_POST['be']);
$bu = preg_replace("[^a-z]", "", $_POST['bu']);
$se = preg_replace("[^a-z]", "", $_POST['se']);
// Check to see if the user filled all fields with
// the "Required"(*) symbol next to them in the join form
// and print out to them what they have forgotten to put in
if((!$username) || (!$firstname) || (!$surname) || (!$accounttype) || (!$b_m) || (!$b_d) || (!$b_y) || (!$email) || (!$password)){
$errorMsg = "You did not submit the following required information!<br /><br />";
if(!$username){
$errorMsg .= "--- User Name";
} else if(!$accounttype){
$errorMsg .= "--- Account Type";
} else if(!$b_m){
$errorMsg .= "--- Birth Month";
} else if(!$b_d){
$errorMsg .= "--- Birth Day";
} else if(!$b_y){
$errorMsg .= "--- Birth year";
} else if(!$firstname){
$errorMsg .= "--- First Name";
} else if(!$surname){
$errorMsg .= "--- Surname";
} else if(!$email){
$errorMsg .= "--- Email Address";
} else if(!$password){
$errorMsg .= "--- Password";
}
} else {
// Database duplicate Fields Check
$sql_username_check = mysql_query("SELECT id FROM memberstable WHERE username='$username' LIMIT 1");
$sql_email_check = mysql_query("SELECT id FROM memberstable WHERE email='$email' LIMIT 1");
$username_check = mysql_num_rows($sql_username_check);
$email_check = mysql_num_rows($sql_email_check);
if ($username_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your User Name is already in use inside our system. Please try another.";
} else if($email_check > 0){
$errorMsg = "<u>ERROR:</u><br />Your Email address is already in use inside our system. Please try another.";
} else {
// Add MD5 Hash to the password variable
$hashedPass = md5($password);
// Convert Birthday to a DATE field type format(YYYY-MM-DD) out of the month, day, and year supplied
$full_birthday = "$b_y-$b_m-$b_d";
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO memberstable (username, firstname, surname, accounttype, email, birthday, password)
VALUES('$username','$firstname','$surname','$accounttype','$email','$full_birthday','$hashedPass')") or die (mysql_error());
// Get the inserted ID here to use in the activation email
$id = mysql_insert_id();
// Create directory(folder) to hold each user files(pics, MP3s, etc.)
mkdir("memberFiles/$id", 0755);
// Start assembly of Email Member the activation link
$to = "$email";
// Change this to your site admin email
$from = "admin#getscene.com";
$subject = "Complete your registration";
//Begin HTML Email Message where you need to change the activation URL inside
$message = '<html>
<body bgcolor="#FFFFFF">
Hi ' . $firstname . ',
<br /><br />
You must complete this step to activate your account with us.
<br /><br />
Please click here to activate now >>
<a href="http://www.getscene.com/activation.php?id=' . $id . '">
ACTIVATE NOW</a>
<br /><br />
Your Login Data is as follows:
<br /><br />
E-mail Address: ' . $email . ' <br />
Password: ' . $password . '
<br /><br />
Thanks!
</body>
</html>';
// end of message
$headers = "From: $from\r\n";
$headers .= "Content-type: text/html\r\n";
$to = "$to";
// Finally send the activation email to the member
mail($to, $subject, $message, $headers);
// Then print a message to the browser for the joiner
header( 'Location: http://localhost/urshow/registrationsuccess.php' ) ;
// Exit so the form and page does not display, just this success message
} // Close else after database duplicate field value checks
} // Close else after missing vars check
} //Close if $_POST
?>
for the html i have
<!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>Getscene registration</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
</script>
</head>
<body>
<?php include_once "header_template.php"; ?>
<style type="text/css">
#account_types > div { display: none; }
</style>
<div id="signupwrapper">
<div id="signupinner">
<h3 align="left"> GETSCENE REGISTRATION ! </h3>
<hr />
<div id="signup" style="border:thin; border-color:#666">
<h4 align="left">Please Choose One of The Following Account Types</h4>
<div id="accountswrapper">
<form id="accountchoice" name="accountchoice" method="post" action="">
<label for="personalfan">personal/fan</label>
<input type="radio" name="pf" id="personalfan" value="radio1" checked="checked" />
<label for="soloartist">Solo artist</label>
<input type="radio" name="sa" id="soloartist" value="radio2" />
<label for="band">band</label>
<input type="radio" name="ba" id="band" value="radio3" />
<label for="venue">venue</label>
<input type="radio" name="ve" id="venue" value="radio4" />
<label for="business">business</label>
<input type="radio" name="bu" id="business" value="radio5" />
<label for="service">service</label>
<input type="radio" name="se" id="service" value="radio6" />
</form>
<hr />
<div id="account_types">
<div class="personalfan">
<table width="400" border="0" align="center">
<form action="regpersonal.php" method="post" enctype="multipart/form-data">
<tr>
<td colspan="2"><?php echo "$errorMsg"; ?></td>
</tr>
<tr>
<td><div align="right">Username:</div></td>
<td><label for="username"></label>
<input name="username" type="text" id="username" size="30" /></td>
</tr>
<tr>
<td width="146"><div align="right">First Name:</div></td>
<td width="244"><label for="firstname"></label>
<input name="firstname" type="text" id="firstname" size="30" /></td>
</tr>
<tr>
<td><div align="right">Surname:</div></td>
<td><label for="surname"></label>
<input name="surname" type="text" id="surname" size="30" /></td>
</tr>
<tr>
<td><div align="right">Email Address:</div></td>
<td><label for="email"></label>
<input name="email" type="text" id="email" size="30" /></td>
</tr>
<tr>
<td><div align="right">Password:</div></td>
<td><label for="password"></label>
<input name="password" type="password" id="password" size="30" /></td>
</tr>
<tr>
<td><div align="right">Date Of Birth:</div></td>
<td>
<select name="birth_day" class="formFields" id="birth_day">
<option value='01'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
<option value='04'>04</option>
<option value='05'>05</option>
<option value='06'>06</option>
<option value='07'>07</option>
<option value='08'>08</option>
<option value='09'>09</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
<option value='13'>13</option>
<option value='14'>14</option>
<option value='15'>15</option>
<option value='16'>16</option>
<option value='17'>17</option>
<option value='18'>18</option>
<option value='19'>19</option>
<option value='20'>20</option>
<option value='21'>21</option>
<option value='22'>22</option>
<option value='23'>23</option>
<option value='24'>24</option>
<option value='25'>25</option>
<option value='26'>26</option>
<option value='27'>27</option>
<option value='28'>28</option>
<option value='29'>29</option>
<option value='30'>30</option>
<option value='31'>31</option>
</select>
<select name="birth_month" class="formFields" id="birth_month">
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='04'>April</option>
<option value='05'>May</option>
<option value='06'>June</option>
<option value='07'>July</option>
<option value='08'>August</option>
<option value='09'>September</option>
<option value='10'>October</option>
<option value='11'>November</option>
<option value='12'>December</option>
</select>
<select name="birth_year" class="formFields" id="birth_year">
<option value='2012'>2012</option>
<option value='2011'>2011</option>
<option value='2010'>2010</option>
<option value='2009'>2009</option>
<option value='2008'>2008</option>
<option value='2007'>2007</option>
<option value='2006'>2006</option>
<option value='2005'>2005</option>
<option value='2004'>2004</option>
<option value='2003'>2003</option>
<option value='2002'>2002</option>
<option value='2001'>2001</option>
<option value='2000'>2000</option>
<option value='1999'>1999</option>
<option value='1998'>1998</option>
<option value='1997'>1997</option>
<option value='1996'>1996</option>
<option value='1995'>1995</option>
<option value='1994'>1994</option>
<option value='1993'>1993</option>
<option value='1992'>1992</option>
<option value='1991'>1991</option>
<option value='1990'>1990</option>
<option value='1989'>1989</option>
<option value='1988'>1988</option>
<option value='1987'>1987</option>
<option value='1986'>1986</option>
<option value='1985'>1985</option>
<option value='1984'>1984</option>
<option value='1983'>1983</option>
<option value='1982'>1982</option>
<option value='1981'>1981</option>
<option value='1980'>1980</option>
<option value='1979'>1979</option>
<option value='1978'>1978</option>
<option value='1977'>1977</option>
<option value='1976'>1976</option>
<option value='1975'>1975</option>
<option value='1974'>1974</option>
<option value='1973'>1973</option>
<option value='1972'>1972</option>
<option value='1971'>1971</option>
<option value='1970'>1970</option>
<option value='1969'>1969</option>
<option value='1968'>1968</option>
<option value='1967'>1967</option>
<option value='1966'>1966</option>
<option value='1965'>1965</option>
<option value='1964'>1964</option>
<option value='1963'>1963</option>
<option value='1962'>1962</option>
<option value='1961'>1961</option>
<option value='1960'>1960</option>
<option value='1959'>1959</option>
<option value='1958'>1958</option>
<option value='1957'>1957</option>
<option value='1956'>1956</option>
<option value='1955'>1955</option>
<option value='1954'>1954</option>
<option value='1953'>1953</option>
<option value='1952'>1952</option>
<option value='1951'>1951</option>
<option value='1950'>1950</option>
<option value='1949'>1949</option>
<option value='1948'>1948</option>
<option value='1947'>1947</option>
<option value='1946'>1946</option>
<option value='1945'>1945</option>
<option value='1944'>1944</option>
<option value='1943'>1943</option>
<option value='1942'>1942</option>
<option value='1941'>1941</option>
<option value='1940'>1940</option>
<option value='1939'>1939</option>
<option value='1938'>1938</option>
<option value='1937'>1937</option>
<option value='1936'>1936</option>
<option value='1935'>1935</option>
<option value='1934'>1934</option>
<option value='1933'>1933</option>
<option value='1932'>1932</option>
<option value='1931'>1931</option>
<option value='1930'>1930</option>
<option value='1929'>1929</option>
<option value='1928'>1928</option>
<option value='1927'>1927</option>
<option value='1926'>1926</option>
<option value='1925'>1925</option>
<option value='1924'>1924</option>
<option value='1923'>1923</option>
<option value='1922'>1922</option>
<option value='1921'>1921</option>
<option value='1920'>1920</option>
<option value='1919'>1919</option>
<option value='1918'>1918</option>
<option value='1917'>1917</option>
<option value='1916'>1916</option>
<option value='1915'>1915</option>
<option value='1914'>1914</option>
<option value='1913'>1913</option>
<option value='1912'>1912</option>
<option value='1911'>1911</option>
<option value='1910'>1910</option>
<option value='1909'>1909</option>
<option value='1908'>1908</option>
<option value='1907'>1907</option>
<option value='1906'>1906</option>
<option value='1905'>1905</option>
<option value='1904'>1904</option>
<option value='1903'>1903</option>
<option value='1902'>1902</option>
<option value='1901'>1901</option>
<option value='1900'>1900</option>
</select></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="submit" id="submit" value="Submit" /></td>
</tr>
</form>
</table></div>
<div class ="soloartist"></div>
<div class="band"></div>
<div class="venue"></div>
<div class="business"></div>
<div class="service"></div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#accountchoice').change(function() {
var divToShow = $(this).find('input:checked').attr('id');
$('#account_types > div').each(function() {
if($(this).hasClass(divToShow)) { $(this).show(); }
else { $(this).hide();}
});
});
$('#accountchoice').trigger('change');
});
</script>
<?php include_once "footer_template.php"; ?>
</body>
</html>
ad in mysql my table has a field called accounttype, which as i said uses an enum format this is the row
accounttype enum('a', 'b', 'c', 'd', 'e', 'f', 'g' one set spare for admin
what would i need for php to get the selected radio button to set account type based on the radios value. i have little to no previous use of radio buttons and have tried a few things but they all fail.
any help here would be a godsend
edited to show all code
1) You have to have one form - you don't have any action associated with the first form - those radio buttons should be within the form that has an action associated (php file). action="" means it's processed by current page - which actually doesn't do any processing.
2) You do keep THE SAME name for all radio buttons.
3) You make that name 'accounttype' as that's what you use to assign a value. (and you don't need any preg_replace there).
4) Run all of your data through mysql_real_escape_string, not just the email.
if you are using any library (jquery) you can do this easily.
(function($){
$('#accountchoice').find('input').change(function(){
if(this.checked){
if($(this).val() == 'radio1'){
// do the needed ajax for radio1 is selected
}
// add conditions for all the radio buttons here, or you can use a swicth case too.
}
});
})(jQuery);
<input type="radio" name="luckynumber" value="1" />
<input type="radio" name="luckynumber" value="2" />
In php
print_r($_POST['luckynumber']);

Categories