how to insert multiple array into database using PHP - php

I need help. What seems to be the problem with our php codes? We can't seem to insert our data into our database. I'm just a beginner and I'm tasked to store multiple data into multiple arrays into our database. What we're actually doing is to enter a number (ex: 5) and 5 forms should show within that page. each form would consist of name address and tel phone number. after that we submit it to our database. We have already controlled hot many forms to show but we weren't able to store the data inserted. Can anyone help us please? Thank you.
form.php
<form method="POST" action="form.php">
<input type="text" name="waw" />
<input type="submit" />
<?php
$i=0;
while ($i<$_POST['waw'])
{
?>
</form>
<form method="POST" action="input.php">
<!-- Person #1 -->
<input type="text" name="username[]" />
<input type="text" name="phonenum[]" />
<input type="text" name="add[]" />
<?php
$i++;
}
?>
<input type="submit" />
</form>
input.php
<?php
$username="maizakath";
$password="12345";
$database="tryinsert";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die("<b>Unable to specified database</b>");
$sql_start = 'INSERT INTO `mytable` VALUES ';
$sql_array = array();
$queue_num = $_POST['waw'];
foreach ($_POST['username'] as $row=>$name)
{
$username = $name;
$phonenum = $_POST['phonenum'][$row];
$add = $_POST['add'][$row];
$sql_array[] = '(' . $username . ', ' . $phonenum . ', ' . $add . ')';
if (count($sql_array) >= $queue_num)
{
mysql_query($sql_start . implode(', ', $sql_array));
$sql_array = array();
}
}
if (count($sql_array) > 0)
{
mysql_query($sql_start . implode(', ', $sql_array))or die(mysql_error());
}
?>

I've modified your code to make it work:
form.php
<form method="POST" action="form.php">
<input type="text" name="waw" />
<input type="submit" />
</form>
<form method="POST" action="input.php">
<?php
$i=0;
while ($i<$_GET['waw'])
{
?>
<!-- Person #1 -->
<input type="text" name="username[]" />
<input type="text" name="phonenum[]" />
<input type="text" name="add[]" /><br />
<?php
$i++;
}
?>
<input type="submit" />
</form>
input.php
<?php
$username="maizakath";
$password="12345";
$database="tryinsert";
mysql_connect('localhost',$username,$password);
#mysql_select_db($database) or die("<b>Unable to specified database</b>");
$sql_start = 'INSERT INTO `mytable` VALUES ';
$sql_array = array();
$queue_num = $_POST['waw'];
foreach ($_POST['username'] as $row=>$name)
{
$username = $name;
$phonenum = $_POST['phonenum'][$row];
$add = $_POST['add'][$row];
$sql_array[] = '("' . $username . '", "'.$phonenum.'", "'.$add.'")';
if (count($sql_array) >= $queue_num) {
$query_single=$sql_start . implode(', ', $sql_array);
mysql_query($query_single);
$sql_array = array();
}
}
if (count($sql_array) > 0) {
$query = $sql_start . implode(', ', $sql_array);
mysql_query($query)or die(mysql_error());
}
?>
It works fine. I've just tested it on my local machine.
EDIT(Comments):
Usage of variable $queue_num in input.php is senseless, because this variable is available only in form.php script('wow' input placed in another form, which is submitted to file form.php, not input.php). So if (count($sql_array) >= $queue_num) block works wrong;
Check your config settings for the database connection(as I've wrote in comment, you have to define constant with name 'localhost' or enclose word localhost with quotes);
I've modified your form, because it had wrong structure;
I didn't understand the objective of creating first form in form.php.
You can modify this code to make it more appropriate for your case. But firsat of all try to use this one.
Note. Use var_dump() function to see your $_POST array during debugging to understand, what variables are available.

I Had tried its work fine but when inserting into database it will insert null value also if user did'nt filled up the whole field.

I have stored two arrays in one table at the same time. Hope this will help you.
<?php
$i = 0;
foreach($element_name as $element_names){
$element_value = $_POST['element_value'];
$element_names_insert = mysql_query("insert into wp_remote_fields
set
remote_fields = '".$element_names."',
remote_values = '".$element_value[$i]."'
");
$i++;
}
?>

Related

How to make an html/php form?

I have a php file (let's call it first) that stores names in a database. I now have a different php file with a html/php form (let's call it second). How can I make the form (second) input names into my database using my inital php (first) file?
Below is my php form:
<!DOCTYPE HTML>
<HTML>
<head>
<title>PHP FORM</title>
</head>
<body>
<h2>PHP FORM for Process Form</h2>
<form method="post" action="processForm.php">
Name: <input type="text" name="names" required = "required"><br>
<input type="submit" value="Create Users" onclick="formInputNames"><br>
<input type="checkbox" name="activate" value="Activate">Activate
</form>
</body>
</html>
Below is 'php first':
$nameList = 'Obi One, Not Naw, Lent Over, Foo Bar';
$newerName = 'Green Sauce';
$nameList = newUse($newerName,$nameList);
$email = '#email.org';
$fullnames = explode(" ",$nameList);
function newUse($nep, $nameList){
if($nep == empty($nameSplit[0]) && empty($nameSplit[1]) || empty($newName)){
return "$nameList, $nep";
}
return $nameList;
}
/*I open the database here*/
foreach ($fullnames as $fullname){
$nameSplit = explode(" ", $fullname);
if ($nameList == empty($nameSplit[0]) || empty($nameList)){
echo 'No First Name Here Or No Name At All';
echo '<br>';
echo '<br>';
} elseif ($nameList == empty($nameSplit[1])){
echo 'No Last Name Here';
echo '<br>';
echo '<br>';
} else{
$firstName = $nameSplit[0];
$lastName = $nameSplit[1];
$emailUser = $nameSplit[0].$email;
echo 'First Name: ' . $firstName;
echo '<br>';
echo 'Last Name: ' . $lastName;
echo '<br>';
echo 'Email Address: ' . $firstName . $email;
echo '<br>';
echo '<br>';
}
$queryString = "INSERT INTO `project`.`user`
(`id`, `firstName`, `lastName`, `email`, `activated`, `date_created`)
VALUES
(NULL, '$firstName', '$lastName', '$emailUser', '0', NOW())";
$result = mysqli_query($conn, $queryString)
or die (mysqli_error($conn));
}
I'm new to php and I'm really at a lost here. I'm pretty sure I need to use POST but I don't really understand how. Please help me out. Thank You.
Everything I have googled has not helped me and some of the similar questions on this site have not either. I need help.
You seem to have problem only with how to post the values, So your HTML file:
<form method="post" action="processForm.php">
First Name: <input type="text" name="firstname">
Second Name: <input type="text" name="lastname">
<input type="submit" value="Submit">
</form>
Your PHP file:
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$name = $firstName ." ". $lastName;
//Code for adding the values to the database.
If you put your function at the top of your processForm.php above where it is called it could be
// I am assuming this comes from your database
$nameList = 'Obi One, Not Naw, Lent Over, Foo Bar';
$newerName = $_POST['names'];
$email = '#email.org';
function newUse($nep, $nameList){
$nameSplit = array();
$nameSplit = explode(" ", $nep);
if(!empty($nameSplit[0]) && !empty($nameSplit[1]){
return "$nameList, $nep";
}
return $nameList;
}
$nameList = newUse($newerName,$nameList);
// need to explode on comma into name pairs with spaces or there will be nothing to explode into $nameSplit later.
$fullnames = explode(',', $nameList);
It might be worth making two text boxes - one for firstname name="firstname" and one for second name name="secondname", then putting the two together as in
$newerName = $_POST['firstname'] . " " . $_POST['secondname'];
This would ensure that you would reduce the risk of people putting two spaces or something else unwanted separating their names that would make your explode(); fail.
$newerName = mysqli_real_escape_string($newerName);
Before you put it into the function will help eliminate some of the security problems but it is not infallible.
The HTML would be
<form method="post" action="processForm.php">
First Name: <input type="text" name="firstname" required /><br />
Second Name: <input type="text" name="secondname" required /><br />
<input type="submit" value="Create Users" /><br />
<input type="checkbox" name="activate" value="Activate" />Activate
</form>
You could give your checkbox a value of 1 and pick that up as $activate = intval($_POST['activate']); where the forcing to integer will have the effect of cleaning it up. You could then use that as a variable where you currently have '0' in your MySql.

Update SQL data within PHP

Ok i have updated my Code, not getting any Errors but nothing is being updated on the mysql side nor on the PHP Front end.
I have even tried a Hard Coded Statment.
This section is at the Very top of my Php Viewer page..
<?php
/
/ IF RESQUEST IS EQUAL TO SUBMUIT
if (isset($_REQUEST['submit']))
{
$my_date = date("Y-m-d H:i:s");
$order = uniqid();
$FullName= $_REQUEST['fullname'];
//Take in full Name and Split it into first and last name.
list($fname, $lname ) = explode( ' ', $customerName, 2 );
$address = $_REQUEST['address'];
$emailAddress = $_REQUEST['emailAddress'];
$phoneNo = $_REQUEST['phoneNo'];
Below is my Sticky Forum which is getting the Information from the Database and putting it into the Text Fields
// STICKY FORM TO ALLOW USER TO UPDATE INFORMATION
if (isset($_REQUEST['up']))
{
$query_sticky = mysqli_query($connection,'SELECT * FROM orders WHERE id = "' . $_GET['id'] . '"');
if(! $query_sticky )
{
die('Could not get data: ' . mysqli_error($connection)); // Could not find Order_id show Error
}//end die error
else
(isset($_REQUEST['update']));
{
while($row = mysqli_fetch_array($query_sticky, MYSQLI_ASSOC))
{
$row['id'];
echo '<form action="" method="post">'
Name:';
echo'<input name="customerName" id="cname" type="text" required value="'.$row['firstname']. " " .$row['lastname']. '" />';
echo' <br/>
<br/>
Address:
<textarea name="address" id = "caddress" type="text" rows="5" cols="30" required value="'.$row['address'].'" ></textarea>
<br/>
<br/>
Email Address:
<input name="emailAddress" type="email" required value="'.$row['email']. '" />
<br/>
<br/>
<br/>
Phone Number:
<input name="phoneNo" id="phoneNumber" type="text" required value="'.$row['phone']. '" />
<br/>
<br/>
<button type="submit" name="update" value="update" >update</button
<div id="Submit">
</form>
<form action="order.php" method="delete">
</form>';
}//close if
}
} // Close While
here is my Update Section
if (isset($_REQUEST['update']))
{
$updateDB = "UPDATE orders SET student ='$_POST[student]',
firstname='John', lastname='wallace',
email = '$_POST[emailAddress]', address = '$_POST[address]',
phone = '$_POST[phoneNo]'
WHERE
order_id ='$_GET[order_id]'";
mysqli_query($connection, $updateDB);
}//end update..
}//end PHP
?>
You were mixing up single and double quotes in your UPDATE query string. Try this instead:
$updateDB = "UPDATE test
SET email = '".#$_POST[$emailAddress]."',
address = '".#$_POST[$address]."',
phone = '".#$_POST[$phoneNo]."'
WHERE id = '".$_GET['id']."'";

Inserting HTML form submissions into MySQL table (using PDO)

I'm trying to create a webpage that has multiple forms that people will fill, click submit, PHP will handle running a query to insert all the data into the table, in their respective fields.
I created one that submitted one field completely fine, and as soon as I expanded it to 5 fields I realised I didn't know how to handle the code.
<html>
<head>
<title>Asset Pass</title>
</head>
<body>
<h1>Asset Submission</h1>
<p>Connection status: <?php include '../mysqlconnect.php'; echo $db . " active"; ?></p>
<form method="post">
<div><label for="type">Type:
<br/><input type="text" name="type" id="type"/></label></div>
<div><label for="name">Name:
<br/><input type="text" name="name" id="name"/></label></div>
<div><label for="desc">Description:
<br/><input type="text" name="desc" id="desc"/></label></div>
<div><label for="loc">Location:
<br/><input type="text" name="loc" id="loc"/></label></div>
<div><label for="label">Label:
<br/><input type="text" name="label" id="label"/></label></div>
<div><input type="submit" name="submit" value="GO"/></div>
</form>
<?php
#function aquery($asset) {
# include '../mysqlconnect.php';
# $conn->query("INSERT INTO kit VALUES ('$asset', '$name', '$desc', '$loc', '$label');");
#}
if ($_POST['submit']) {
include '../mysqlconnect.php';
foreach ($_POST['type'] as $key => $value)
{
$type = $_POST['type'] [$key];
$name = $_POST['name'] [$key];
$desc = $_POST['desc'] [$key];
$loc = $_POST['loc'] [$key];
$label = $_POST['label'][$key];
$sql = $conn->query("INSERT INTO Kit VALUES ('$type', '$name', '$desc', '$loc', '$label');");
}
}
## $asset = $_POST['name'];
# aquery($asset);
# printf("<h3>Entry Accepted</h3>" . "<br/><br/>" . "<strong>Submission: </strong>" . $asset . "<br/><br/>");
?>
</body>
</html>
Sorry for the butchered code - the commented bits at the top and bottom are the original fragments of code I tried using, the bit in the middle is a suggested online solution, and something close to what I think would work. I'm using PDO btw!
Didn't understand how $_POST and isset worked properly.
if (isset($_POST['submit']))
{
include '../mysqlconnect.php';
$type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_MAGIC_QUOTES);
and so forth, works perfectly.

PHP - editing data in db issue

I'm going to keep it short and simple. I'm writing a really basic code in php which adds content to mysql db and I've run into an issue with editing. This is my form:
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
And this is my editIt.php
//session start and stuff
if(filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_STRING) == "POST")
{
echo "<script type='text/javascript'>alert('EDITIT!');</script>";
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("WebSiteDB") or die ("Cannot connect to database");
$id = $_POST['id'];
$details = mysql_real_escape_string($_POST['details']);
$time = strftime("%X");
$date = strftime("%B %d, %Y");
$isPublic = 'no';
foreach($_POST['public'] as $eachCheck)
{
if($eachCheck != NULL)
$isPublic = "yes";
}
mysql_query("UPDATE list SET details='$details', dateEdited='$date', timeEdited= '$time', public='$isPublic' WHERE id='$id'");
header("location: home.php");
}
I can't really find an issue with this code (which is not really strange, I'm a newbie at web stuff) and yet it just goes to home.php and does not change data in DB. Please, help me jump this ledge, so I can go on with my life.
I think, the problem is in this line $id = $_POST['id'];. On form submit, the input field value will only be submitted, not the DIV value.
So, please change from :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
To :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<input type="hidden" name="id" value="' . $id . '">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}

How to add action tag to form?

I have a working php guestbook script. It's only 1 file. I tried to validate it and there is only one error:
Line 147, Column 36: required attribute "action" not specified
<form method="post" name="blogform">
Now the code is this and I'm sure I would need to break up the file to two so that I can create a file for the action tag but I just don't know how. Any help is much appreciated.
<?php
session_start();
include("../../4a/inc/opendb.inc.php");
if(isset($_POST['send'])) //checks if $_POST variable "is set"
if(isset($_SESSION["ellenorzo"]) && !empty($_SESSION["ellenorzo"]) && $_SESSION["ellenorzo"]==$_POST["code"]){
$name = trim($_POST['name']); //eliminating whitespaces
$email = trim($_POST['email']);
$message = addslashes( trim($_POST['message']));
$query = "INSERT INTO blog (name, email, message, date) " .
"VALUES ('$name', '$email', '$message', NOW())";
mysql_query($query) or die('Hey, something is wrong!' . mysql_error());
header('Location: ' . $_SERVER['REQUEST_URI']);
exit;
}
?>
<?php
include('../../4a/inc/head.inc.php');
?>
<body style="color: #ffffff;">
<div class="mainblog">
<div class="top">
<div class="menu">
<?php
include('../menu.inc.php');
?>
</div>
</div>
<div class="middleblog">
<form method="post" name="blogform">
<input name="name" id="name" class="nameblog" type="text" />
<img src="../../4a/img/main/name.jpg" class="name" alt="Name" />
<input name="email" id="email" class="emailblog" type="text" />
<img src="../../4a/img/main/email.jpg" class="email" alt="Email" />
<textarea name="message" id="message" class="messageblog" rows="6" cols="6" onkeyup="return ismaxlength(this)">
</textarea>
<img src="../../4a/img/main/message.jpg" class="message" alt="Message" />
<input name="send" value="submit" id="send" class="sendblog" type="image" src="../../4a/img/main/send.jpg" onclick="return checkform();" />
<input type="hidden" name="send" value="submit" />
<div class="text_check_code">
<font class="text">
Enter the characters as they are shown below.
</font>
</div>
<img src="../../4a/inc/secure.inc.php" class="img_check_code" alt="Nospam" />
<input name="code" class="input_check_code" />
</form>
<?php
$rowsperpage = 10;
$pagenumber = 1;
if(isset($_GET['page']))
{
$pagenumber = $_GET['page'];
}
$offset = ($pagenumber - 1) * $rowsperpage;
$query = "SELECT id, name, email, message, date ".
"FROM blog ".
"ORDER BY id DESC ".
"LIMIT $offset, $rowsperpage";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
if(mysql_num_rows($result) == 0)
{
print("<br /><br /><br /><br /><br /><br /><br /><br />The blog is empty.");
}
else
{
while($row = mysql_fetch_array($result))
{
list($id, $name, $email, $message, $date) = $row;
$name = htmlspecialchars($name);
$email = htmlspecialchars($email);
$message = htmlspecialchars($message);
$message = stripslashes(nl2br($message)); //real breaks as user hits enter
?>
<br />
<div class="blogentries">
<b><?=$name?></b>
<br />
<?=$message?>
<br />
<i><?=$date?></i>
</div>
<br />
<?php
} //closing while statement
$query = "SELECT COUNT(id) AS numrows FROM blog";
$result = mysql_query($query) or die('Hey, something is wrong!. ' . mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxpage = ceil($numrows/$rowsperpage); //rounding up any integer eg. 4,1=5
$nextlink = '';
if($maxpage > 1)
{
$self = $_SERVER['PHP_SELF'];
$nextlink = array();
for($page = 1; $page <= $maxpage; $page++)
{
$nextlink[] = "$page";
}
$nextlink = "Next: " . implode(' ยป ', $nextlink); //returns all elements of an array as a string
}
include ("../../4a/inc/closedb.inc.php");
?>
<br />
<div class="nextlink">
<?=$nextlink;?>
</div>
</div>
<br />
<br />
<div class="bottomblog">
<?php
require_once('../../4a/inc/copyright.inc.php');
?>
</div>
<br />
<br />
</div>
<?php //closing the else statement
}
?>
<?php
include('../../4a/inc/footer.inc.php');
?>
The action property specifies the link the form is sent to. If the form calls itself you can leave it blank:
<form action="" method="post" name="blogform">
The action tag tells the form where to submit the data. If it is left blank, it will attempt to submit the data to the current php page. If it's giving you trouble, perhaps you need to specify it and point it to the php page that generates the form.
In the code you provided, the bit of code which handles new inserts is at the top of this page, so you should set the action tag to be the name of the page.
By the way, you should ensure that your inputs are all cleaned; just using trim() before inserting them is asking for trouble. See here for more on this topic.

Categories