I'm new with Codeigniter and I'm having some trouble inserting arrays into my database. An error kept popping out that I can't insert array to my database.
Here's my HTML form:
<?= form_open('profile/profile_submit'); ?>
<table class="table table-hover table-striped table-responsive">
<thead>
<tr>
<th id="headCheckHide"></th>
<th><center>Name</center></th>
<th><center>Date of Birth</center></th>
<th><center>Occupation</center></th>
<th><center>Educ. attainment</center></th>
</tr>
</thead>
<tbody id="sibTable">
<tr class="product-item">
<td>
<input type="text" class="form-control form-input" name="siblingName[]">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingBirthDate[]">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingOccupation[]">
</td>
<td>
<select class="form-control form-input" name="siblingEducAttainment[]" >
<option value="" selected>-Please select-</option>
<option value="less than high school">less than high school</option>
<option value="Some college but no degree">Some college but no degree</option>
<option value="Associates Degree">Associates Degree</option>
<option value="Elementary Graduate">Elementary Graduate</option>
<option value="Secondary Graduate">Secondary Graduate</option>
<option value="College Graduate">College Graduate</option>
<option value="Master's Degree">Master's Degree</option>
<option value="Professional Degree">Professional Degree</option>
<option value="Doctorate Degree">Doctorate Degree</option>
</select>
</td>
</tr>
</tbody>
</table>
<?= form_submit('submit','Save', 'class="btn btn-outline-primary waves-effect"');?>
<?php echo form_close();?>
My Controller for the form
public function profile_submit(){
$siblings=array(
'name' => $this->input->post('siblingName'),
'birthDate' => $this->input->post('siblingBirthDate'),
'occupation' => $this->input->post('siblingOccupation'),
'educAttainment' => $this->input->post('siblingEducAttainment')
);
$this->profile_model->submit_profile($siblings);
redirect('profile','refresh'); //name of the html file
}
My model for (profile_model.php)
function submit_profile($siblings){
$this->db->insert('tbl_st_profile_sibling',$siblings);
}
this is my model with the error: can't insert array into database.
Can anyone please help? thank you.
I think you need to insert multiple input data at a time with the same name, don't worry please follow my instructions as given below
Changes in Controller:
public function profile_submit(){
$submit_status = $this->profile_model->submit_profile();
if( $submit_status == "TRUE"){
redirect('profile','refresh'); //name of the html file
}else{
// Do Something else..
}
}
Changes in Model:
function submit_profile(){
$siblingsCount = count($this->input->post('siblingName'));
if($siblingsCount != null){
$itemValues=0;
$query = "INSERT INTO tbl_st_profile_sibling(name,birthDate,occupation,educAttainment) VALUES ";
$queryValue = "";
for($i=0;$i<$siblingsCount;$i++) {
$name = $this->input->post('name');
$birthDate = $this->input->post('birthDate');
$occupation = $this->input->post('occupation');
$educAttainment = $this->input->post('educAttainment');
if(!empty($name[$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $name[$i] . "', '" . $birthDate[$i] . "', '" . $occupation[$i] . "', '" . $educAttainment[$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
if (!$this->db->query($sql)) {
echo "FALSE";
}else {
echo "TRUE";
}
}
}
}
I hope this may help you...Thanks!
If you need to store array data into DB you need to use loops to insert one.
function submit_profile($siblings){
foreach($siblings['name'] as $key => $siblingName) {
$dataToSave = array(
'name' => $siblingName,
'birthDate' => $siblings['siblingBirthDate'][$key],
'occupation' => $siblings['siblingOccupation'][$key],
'educAttainment' => $siblings['siblingEducAttainment'][$key]
);
$this->db->insert('tbl_st_profile_sibling', $dataToSave);
}
}
UPDATE : Even you can use insert_batch to skip insertion in loop
function submit_profile($siblings){
foreach($siblings['name'] as $key => $siblingName) {
$dataToSave[] = array(
'name' => $siblingName,
'birthDate' => $siblings['siblingBirthDate'][$key],
'occupation' => $siblings['siblingOccupation'][$key],
'educAttainment' => $siblings['siblingEducAttainment'][$key]
);
}
$this->db->insert_batch('tbl_st_profile_sibling', $dataToSave);
}
The issue is not with the array you are saving into database the actual issue is with the post fields thy are in array format siblingName[]. So you need to convert then into strings so that this can be saved easily.
convert the array into coma separated list and then save in database.
$siblingName = implode(",",$_POST['siblingName']);
$siblingBirthDate= implode(",",$_POST['siblingBirthDate']);
$siblingOccupation= implode(",",$_POST['siblingOccupation']);
$siblingEducAttainment= implode(",",$_POST['siblingEducAttainment']);
$siblings=array(
'name' => $siblingName,
'birthDate' => $siblingBirthDate,
'occupation' => $siblingOccupation,
'educAttainment' => $siblingEducAttainment
);
<input type="hidden" name="count" value="<?php echo count($var); ?>" />
for($i=0;$i < count($var);$i++)
{
<tr class="product-item">
<td>
<input type="text" class="form-control form-input" name="siblingName<?php echo $i; ?>">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingBirthDate<?php echo $i; ?>">
</td>
<td>
<input type="text" class="form-control form-input" name="siblingOccupation<?php echo $i; ?>">
</td>
<td>
<select class="form-control form-input" name="siblingEducAttainment<?php echo $i; ?>" >
<option value="" selected>-Please select-</option>
<option value="less than high school">less than high school</option>
<option value="Some college but no degree">Some college but no degree</option>
<option value="Associates Degree">Associates Degree</option>
<option value="Elementary Graduate">Elementary Graduate</option>
<option value="Secondary Graduate">Secondary Graduate</option>
<option value="College Graduate">College Graduate</option>
<option value="Master's Degree">Master's Degree</option>
<option value="Professional Degree">Professional Degree</option>
<option value="Doctorate Degree">Doctorate Degree</option>
</select>
</td>
</tr>
}
$count = $this->input->post('count');
for($i=0;$i < $count;$i++)
{
$siblings=array(
'name' => $this->input->post('siblingName'.$i),
'birthDate' => $this->input->post('siblingBirthDate'.$i),
'occupation' => $this->input->post('siblingOccupation'.$i),
'educAttainment' => $this->input->post('siblingEducAttainment'.$i)
);
$this->profile_model->submit_profile($siblings);
}
Related
I don't know how to add a double record to db.
I have form with double same row content.
I would like to add a dynamic line in the next step using js but at this point I used double html to validate it.
<form class="formAddCoupon" action="/?dashboard=coupon" method="post">
<div class="windowEvents">
<div class="row">
<input type="text" class="teamInput" name="team1">
<input type="text" class="teamInput" name="team2">
<select name="score" id="selectOptions">
<option value="Liczba bramek">Liczba bramek</option>
<option value="Liczba rzutów rożnych">
Liczba rzutów rożnych</option>
<option value="Ilość kartek">Liczba kartek</option>
<option value="Wygrana drużyny">Wygrana drużyny</option>
<option value="Wygrana drużyny lub połowy">
Wygrana drużyny lub połowy</option>
<option value="Wygrana połowy">Wygrana jednej z połów</option>
<option value="Hendicap">Hendicap</option>
<option value="Ilość punktów">Liczba punktów</option>
</select>
<input type="text" class="scoreInput" name="type_score">
</div>
<div class="row">
<input type="text" class="teamInput" name="team1">
<input type="text" class="teamInput" name="team2">
<select name="score" id="selectOptions">
<option value="Liczba bramek">Liczba bramek</option>
<option value="Liczba rzutów rożnych">
Liczba rzutów rożnych</option>
<option value="Ilość kartek">Liczba kartek</option>
<option value="Wygrana drużyny">Wygrana drużyny</option>
<option value="Wygrana drużyny lub połowy">
Wygrana drużyny lub połowy</option>
<option value="Wygrana połowy">Wygrana jednej z połów</option>
<option value="Hendicap">Hendicap</option>
<option value="Ilość punktów">Liczba punktów</option>
</select>
<input type="text" class="scoreInput" name="type_score">
</div>
</div>
<div class="valueAmountRow">
<input
type="number"
name="bid_amount"
id="bid_amount"
placeholder="Stawka"
min="0"
step="any"
>
<input
type="number"
name="winner_amount"
id="winner_amount"
placeholder="Wygrana"
min="0"
step="any"
>
<input type="submit" value="Dodaj">
</div>
</form>
Controller.php:
$data = $this->getRequestPost();
If(!empty($data)) {
$couponData = [
'bid_amount' => $data['bid_amount'],
'winner_amount' => $data['winner_amount'],
'team1' => $data['team1'],
'team2' => $data['team2'],
'score' => $data['score'],
'type_score' => $data['type_score'],
];
$this->db->createCoupon($couponData);
}
Database.php
public function createCoupon(array $data)
{
try {
$this->createNewCoupon($data);
} catch(Throwable $e) {
dump($e);
throw new StorageException('Nie udało się wysłać kuponu', 400, $e);
}
}
private function createNewCoupon($data): void
{
$nr_coupon = trim($this->connection->quote($this->checkIssetCode()));
$created = $this->connection->quote(date('Y-m-d H:i:s'));
$bid_amount = trim($this->connection->quote($data['bid_amount']));
$winner_amount = trim($this->connection->quote($data['winner_amount']));
$team1 = trim($this->connection->quote($data['team1']));
$team2 = trim($this->connection->quote($data['team2']));
$score = trim($this->connection->quote($data['score']));
$typeScore = trim($this->connection->quote($data['type_score']));
$insertNumberCoupon = "INSERT INTO
coupon_number(
nr_coupon,
created,
bid_amount,
winner_amount
)
VALUES(
$nr_coupon,
$created,
$bid_amount,
$winner_amount
)";
$sql_create_number_coupon = $this->connection->prepare($insertNumberCoupon);
if($sql_create_number_coupon)
{
$sql_create_number_coupon->execute();
$id = (int) $this->connection->lastInsertId();
$addEvent = "INSERT INTO
events_at_coupon(
number_id_coupon,
team1,
team2,
score,
type_score
)
VALUES($id,$team1,$team2,$score,$typeScore)";
$sql_add_event_to_table = $this->connection->prepare($addEvent);
if($sql_add_event_to_table)
{
$sql_add_event_to_table->execute();
}
}
}
When i send a form only one record is added to database.
I know why, but what do i have to do to get a double record ?
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".
I have 5 rooms in a table for a guest house and a user must check the room or rooms they wish to book, and select the options they wish to have like the number of people, the breakfast option, dinner option and bed option.
Let's say we call the 5 rooms in order of appearance:
Element Room
Earth Room
Water Room
Air Room
Fire Room
I get option the results if I select the rooms in top to bottom order like Element to Fire rooms, but I get 0 if I select any room inbetween. The room's name always displays correctly when checking them from checkbox, but the option values display 0, except for the first room (Element)
HTML:
<form class="booking-form" name="book-room-form" action="" id="contactForm" method="post" novalidate>
<?php foreach ( $rooms as $room ) : ?>
<input type="checkbox" class="form-check-input" name="room-selected[]" value="<?php echo $room->post_title; ?>">
<select class="num-person select-update" id="<?php echo 'r-' . $room->ID; ?>" name="people-select[]" required>
<option value="0" selected>Select Number of Persons</option>
<option value="1">1 person R600</option>
<option value="2">2 persons R800</option>
</select>
<select class="num-dinner select-update" id="<?php echo 'd-' . $room->ID; ?>" name="dinner-select[]">
<option value="0" selected>Select Dinner Course</option>
<option value="120">Two Course Dinner R120</option>
<option value="200">Three Course Dinner R200</option>
</select>
<select class="num-bf select-update" id="<?php echo 'b-' . $room->ID; ?>" name="breakfast-select[]">
<option value="0" selected>Select Breakfast Type</option>
<option value="70">Basic Breakfast R70</option>
<option value="120">Full Breakfast R120</option>
</select>
<select class="bed-select" name="bed-select[]">
<option selected>Select Bed Size</option>
<option value="King Bed">King Bed</option>
<option value="2 Single Beds">2 Single Beds</option>
</select>
<?php endforeach; ?>
<button name="submit-request" type="submit" class="btn btn-primary">Submit</button>
</form>
CODE:
if(isset($_POST['submit-request'])) {
$room_selected = $_POST['room-selected'];
$numPeople = $_POST['people-select'];
$dinnerSelect = $_POST['dinner-select'];
$breakfastSelect = $_POST['breakfast-select'];
$bedSelect = $_POST['bed-select'];
$room = $room_selected;
$num = $numPeople;
$dinn = $dinnerSelect;
$bf = $breakfastSelect;
$bed = $bedSelect;
foreach ($room as $id => $key) {
//$key returns the room name
if($key) {
$result[$key] = array(
'num_person' => $num[$id],
'dinner' => $dinn[$id],
'breakfast' => $bf[$id],
'bed_type' => $bed[$id],
);
}
echo $key . '<br/>' . $num[$id] . '<br/>' . $dinn[$id] . '<br/>' . $bf[$id] . '<br/>' . $bed[$id] . '<br/>' ;
}
}
I want to be able to select any room and have the option values displayed
I would say its because your not using any keys in your html form arrays. The current solution is a bit fragile so you either need to be more specific in the field naming or include the key in the array.
<?php foreach ( $rooms as $room ) : ?>
<input type="checkbox" class="form-check-input" name="room-selected[]" value="<?php echo $room->post_title; ?>">
<select class="num-person select-update" id="<?php echo 'r-' . $room->ID; ?>" name="people-select[<?php echo $room->post_title; ?>]" required>
<option value="0" selected>Select Number of Persons</option>
<option value="1">1 person R600</option>
<option value="2">2 persons R800</option>
</select>
<select class="num-dinner select-update" id="<?php echo 'd-' . $room->ID; ?>" name="dinner-select[<?php echo $room->post_title; ?>]">
<option value="0" selected>Select Dinner Course</option>
<option value="120">Two Course Dinner R120</option>
<option value="200">Three Course Dinner R200</option>
</select>
<select class="num-bf select-update" id="<?php echo 'b-' . $room->ID; ?>" name="breakfast-select[<?php echo $room->post_title; ?>]">
<option value="0" selected>Select Breakfast Type</option>
<option value="70">Basic Breakfast R70</option>
<option value="120">Full Breakfast R120</option>
</select>
<select class="bed-select" name="bed-select[<?php echo $room->post_title; ?>]">
<option selected>Select Bed Size</option>
<option value="King Bed">King Bed</option>
<option value="2 Single Beds">2 Single Beds</option>
</select>
<?php endforeach; ?>
Then when running your loop instead of checking for $id use the $key.
if(isset($_POST['submit-request'])) {
$room_selected = $_POST['room-selected'];
$numPeople = $_POST['people-select'];
$dinnerSelect = $_POST['dinner-select'];
$breakfastSelect = $_POST['breakfast-select'];
$bedSelect = $_POST['bed-select'];
$room = $room_selected;
$num = $numPeople;
$dinn = $dinnerSelect;
$bf = $breakfastSelect;
$bed = $bedSelect;
foreach ($room as $id => $key) {
//$key returns the room name
if($key) {
$result[$key] = array(
'num_person' => $num[$key],
'dinner' => $dinn[$key],
'breakfast' => $bf[$key],
'bed_type' => $bed[$key],
);
}
echo $key . '<br/>' . $num[$key] . '<br/>' . $dinn[$key] . '<br/>' . $bf[$key] . '<br/>' . $bed[$key] . '<br/>' ;
}
}
I have a problem with php script.
I have an array, which is generated from form, where $_POST['store'] is an array from jQuery form with functionality to add multiple rows:
Array
(
[client] =>
[darvad] =>
[owca] =>
[ldrive] =>
[store] => Array
(
[product] => Array
(
[0] => 430
[1] => 440
[2] => 430
)
[quantity] => Array
(
[0] => 123
[1] => 1223
[2] => 232
)
[segums] => Array
(
[0] => Mixed park
[1] => Light vehicle
[2] => Trucks
)
[deadline] => Array
(
[0] => 2015-08-04
[1] =>
[2] =>
)
[renewal] => Array
(
[0] => 1
)
)
)
And i need to get values from this array into sql insert statment and loop it.
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline)
VALUES (...),(...),(...)....
";
HTML CODE:
<div id="container">
<div id="content" role="main">
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
<form action="<?= $_SERVER['REQUEST_URI'] ?>" method="post" id=multiForm>
<label for="client">Klients: *</label><input id="client" type="text" name="client" placeholder="Reg.nr | Pk.kods" value="" /></br>
<label for="selector1">Darījuma vadītājs: *</label>
<select id="selector1" name="darvad" >
<option value="">-Dar. vadītājs-</option>
<?php
$sql = "SELECT Vards_Uzvards, Tables_ID FROM users";
$results = $wpdb->get_results($sql); // return an object, not ARRAY_N
if ($results) {
foreach ($results as $row) {
echo "<option value = '".$row->Tables_ID."'>".$row->Vards_Uzvards."</option>";
}}
echo "</select></br>";
?>
<label for="owcafind">Meklēt OWCA kodu: *</label><input id="owcafind" type="text" name="owca" placeholder="OWCA Kods (8)" value="" /></br>
<label for="ldrive">Mape L diskā:</label><input id="ldrive" type="text" name="ldrive" placeholder="Mape L diskā" value="" /></br>
Produkti: <img src="<?php echo site_url('/img/plus-icon.png'); ?>" width="15px"><br/>
<table class="multi">
<!-- table title -->
<tr><th>Produkts</th><th>Vienību skaits</th><th>Riska segums:</th><th>Deadline:</th><th>Atjaunojums</th><th>[Option]</th></tr>
<!-- row template, when added new row -->
<tr style="display:none;" class="templateRow">
<td><select name="store[product][]">
<option value="" selected="selected">-Produkts-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
</select></td>
<td><input type="text" name="store[quantity][]" /></td>
<td><select name="store[segums][]">
<option value="" selected="selected">-Riska segums-</option>
<option value="Mixed park">Mixed park</option>
<option value="Light vehicle">Light vehicle</option>
<option value="Trucks">Trucks</option>
<option value="Buss">Buss</option>
</select></td>
<td><input type="date" name="store[deadline][]" class="datepicker" /></td>
<td><input type="checkbox" name="store[renewal][]" value="1" /></td>
<td><a class="del" href="#"><img src="<?php echo site_url('img/minus-icon.jpg'); ?>" width="15px"></a></td>
</tr>
<!-- default values -->
<tr>
<td><select name="store[product][]" >
<option value="" selected="selected">-Produkts-</option>
<option value="430">OCTA</option>
<option value="440">KASKO</option>
</select></td>
<td><input type="text" name="store[quantity][]" /></td>
<td><select name="store[segums][]">
<option value="" selected="selected">-Riska segums-</option>
<option value="Mixed park">Mixed park</option>
<option value="Light vehicle">Light vehicle</option>
<option value="Trucks">Trucks</option>
<option value="Buss">Buss</option>
</select></td>
<td><input type="date" name="store[deadline][]" class="datepicker" /></td>
<td><input type="checkbox" name="store[renewal][]" value="1" /></td>
<td></td>
</tr>
<!-- /default values -->
</table>
From your question, it looks like this is what you're after
$itemCount = sizeof($array['store']['product']);
for ($i = 0; $i < $itemCount; $i++) {
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline) VALUES ("' . $array['store']['product'][$i] . '", "' . $array['store']['quantity'][$i] . '", "' . $array['store']['segums'][$i] . '", "' . $array['store']['deadline'][$i] . '");";
// Run the sql statement on the database here
}
You'll need to ensure that all user-supplied values are properly escaped before storing in the database.
If Array is called $array, then you can access the arrays values like so;
// product;
$array['store']['product'];
// quantity;
$array['store']['quantity'];
// etc.
Then, if they are to go into a single column (which is bad form and I don't recommend, then you can do something like this;
// product;
$prod_string = '';
foreach ($array['store']['product'] as $key => $prod) {
$prod_string .= $prod;
}
Then you can use $prod_string in your query.
OR, if you need to insert a row for EACH of the keys;
// We use the key from the product loop to get the others;
foreach ($array['store']['product'] as $key => $prod) {
$prod_val = $prod;
$qty_val = !empty($array['store']['quantity'][$key]) ? $array['store']['quantity'][$key] : '';
$seg_val = !empty($array['store']['segums'][$key]) ? $array['store']['segums'][$key] : '';
$dl_val = !empty($array['store']['deadline'][$key]) ? $array['store']['deadline'][$key] : '';
// Right here create your query and insert.
$sql_rec = "INSERT INTO tsales_funnel_mrecord (product, quantity, segums, deadline) VALUES ($prod_val, $qty_val, $seg_val, $dl_val);"
// I'm not sure what library you're using for your db management, so will leave that out.
}
Then you'll have the value of each.
NOTE - I have not checked for clean post values. Ie, sanitized input. Thats outside the scope of this question.
Have done it:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// We use the key from the product loop to get the others;
$array = $_POST;
$itemCount = sizeof($array['store']['product']);
// Loop through all $itemCount
$values_string = '';
for ($i = 0; $i < $itemCount; $i++) {
$prod = esc_sql($array['store']['product'][$i]);
$quant = esc_sql($array['store']['quantity'][$i]);
$seg = esc_sql($array['store']['segums'][$i]);
$deadline = esc_sql($array['store']['deadline'][$i]);
$renewal = esc_sql($array['store']['renewal'][$i]);
if ($i < $itemCount - 1) {
$new_str = "('".$prod."','".$quant."','".$seg."','".$deadline."','".$renewal."'),";
} else{
$new_str = "('".$prod."','".$quant."','".$seg."','".$deadline."','".$renewal."');";
}
$values_string .= $new_str;
}
// Run the sql statement on the database here
$sql_rec = "INSERT INTO tsales_funnel_mrecord (Product_type, Vien_skaits, Riska_segums, Deadline, Atjaunojums) VALUES $values_string";
$wpdb->query($sql_rec);
}
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>   </td>
<td> <?php echo $fName ?> </td>
</tr>
<tr>
<td> Last Name: </td>
<td>   </td>
<td> <?php echo $lName ?> </td>
</tr>
<tr>
<td> Address: </td>
<td>   </td>
<td> <?php echo $address ?> </td>
</tr>
<tr>
<td> State: </td>
<td>   </td>
<td> <?php echo $statedropdown ?> </td>
</tr>
<tr>
<td> Zip: </td>
<td>   </td>
<td> <?php echo $zip ?> </td>
</tr>
<tr>
<td> Telephone: </td>
<td>   </td>
<td> <?php echo $phone ?> </td>
</tr>
<tr>
<td> E-mail: </td>
<td>   </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/>';
}