Add multiple inputs with same name to mysql database - php

I'm trying to fill my mysqli database from a form with multiple input fields with the same structure and names using ajax, but I'm pretty stuck here. I have tried several solutions but all with te same result, only my last two input fields are send to my database.
My form looks like this;
<form id="sendform" method="post" action="#">
<fieldset>
<input type="text" value="JD01" id="shortname" name="member[shortname]" readonly />
<input type="text" value="John Doe" id="fullname" name="member[fullname]" readonly />
</fieldset>
<fieldset>
<input type="text" value="JD02" id="shortname" name="member[shortname]" readonly />
<input type="text" value="Jane Doe" id="fullname" name="member[fullname]" readonly />
</fieldset>
<input type="submit" value="Send" />
</form>
The ajax part;
$('#sendform').submit(function(e){
$.ajax({
type: 'POST',
url: 'inc/post.php',
data: $(this).serialize(),
success: function(data){
alert("Data Save: " + data);
}
});
e.preventDefault();
});
And my php;
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', 'root');
define('DBNAME', 'test');
$db = new mysqli(HOST, USER, PASS, DBNAME);
$values = array();
foreach ($_POST['member'] as $member) {
$values[] = '(' . $member['shortname'] . ',' . $member['fullname'] . ')';
}
$sql = "INSERT INTO sendform (shortname, fullname) VALUES " . implode(',', $values);
$result = $db->query($sql);
if($result) {
echo "Yep";
}
$db->close();
What am I doing wrong here? thnx!

Try this:
<form id="sendform" method="post" action="#">
<fieldset>
<input type="text" value="JD01" id="shortname" name="member[shortname][]" readonly />
<input type="text" value="John Doe" id="fullname" name="member[fullname][]" readonly />
</fieldset>
<fieldset>
<input type="text" value="JD02" id="shortname" name="member[shortname][]" readonly />
<input type="text" value="Jane Doe" id="fullname" name="member[fullname][]" readonly />
</fieldset>
<input type="submit" value="Send" />
</form>
And PHP Page:
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', 'root');
define('DBNAME', 'test');
$db = new mysqli(HOST, USER, PASS, DBNAME);
$values = array();
for($i=0 ;$i < count($_POST['member']); $i++) {
$values[] = '("' . $_POST['member']['shortname'][$i] . '","' . $_POST['member']['fullname'][$i] . '")';
}
$sql = "INSERT INTO sendform (shortname, fullname) VALUES " . implode(',', $values);
$result = $db->query($sql);
if($result) {
echo "Yep";
}
$db->close();

You can make the form look like this (note that member[] is now an array itself)
<form id="sendform" method="post" action="">
<fieldset>
<input type="text" value="JD01" id="shortname" name="member[1][shortname]" readonly />
<input type="text" value="John Doe" id="fullname" name="member[1][fullname]" readonly />
</fieldset>
<fieldset>
<input type="text" value="JD02" id="shortname" name="member[2][shortname]" readonly />
<input type="text" value="Jane Doe" id="fullname" name="member[2][fullname]" readonly />
</fieldset>
<input type="submit" value="Send" />
</form>
in your PHP use
foreach ($_POST['member'] as $member) {
$values[] = '(' . $member['shortname'] . ',' . $member['fullname'] . ')';
}

You are using member[shortname] and member[fullname] two times in html. So values from second fieldset are overriding the first one.
Hence we are getting only the values the are put in second fieldset.
You can try using following code:
<form id="sendform" method="post" action="#">
<fieldset>
<input type="text" value="JD01" id="shortname" name="member['shortname'][0]" readonly />
<input type="text" value="John Doe" id="fullname" name="member['fullname'][0]" readonly />
</fieldset>
<fieldset>
<input type="text" value="JD02" id="shortname" name="member['shortname'][1]" readonly />
<input type="text" value="Jane Doe" id="fullname" name="member['fullname'][1]" readonly />
</fieldset>
<input type="submit" value="Send" />
</form>
And my php, make the following changes:
$values = array();
$i = 0;
foreach ($_POST['member'] as $member) {
$values[] = '(' . $member['shortname'][$i] . ',' . $member['fullname'][$i] . ')';
$i++;
}

<td class="text-left"><input type="text" class="form-control input-lg" name="expense[date][]" required placeholder="Enter Date (yy-mm-dd)"></td>
<td class="text-left"><input type="text" class="form-control input-lg" name="expense[msg][]" required placeholder="Enter Expenses Here"></td>
<td class="text-left"><input type="text" class="form-control input-lg" name="expense[vendor][]" required placeholder="Vendor Name Here"></td>
<td class="text-left"><input type="text" class="form-control input-lg" name="expense[amount][]" required placeholder="Enter Amount Here"></td>
<td class="text-left"><input type="text" class="form-control input-lg" name="expense[prove][]" required placeholder="Prove"></td>
PHP Code
<?php
if(isset($_POST['submit'])){
//$date = mysql_real_escape_string($_POST['date']);
//$date = strtotime($date);
// $date = date('Y-m-d', $date);
//$msg = mysql_real_escape_string($_POST['msg']);
//$vendor = mysql_real_escape_string($_POST['vendor']);
//$amount = mysql_real_escape_string($_POST['amount']);
//$prove = mysql_real_escape_string($_POST['prove']);
$values = array();
for($i=0 ;$i < count($_POST['expense']); $i++) {
$values[] = '("' . $_POST['expense']['date'][$i] . '","' . $_POST['expense']['msg'][$i] . '","' . $_POST['expense']['vendor'][$i] . '","' . $_POST['expense']['amount'][$i] . '","' . $_POST['expense']['prove'][$i] . '")';
}
$sql = ("INSERT INTO expenses (date, msg, vendor, amount, prove) VALUES " . implode(',', $values));
echo "<script>alert('Your expenses data inserted successfully!')</script>";
echo "<script>window.open('expenses.php','_self')</script>";
exit();
}
?>
show me the error Notice: Undefiened offset:2 in ..............

Related

PostgreSQL Data Table will not update from PHP code

I am using postgreSQL, PHP, and an HTML form. The form is a simple scholarship application. My connection script seems to work fine because when I click submit on the HTML form it echos "connected" and doesn't die, however no data from the form is transferred to my table. Please any guidance.
My PHP connection script: connect.php
try {
$dbConn = new PDO('pgsql:host=' . DB_HOST . ';'
. 'port=' . DB_PORT . ';'
. 'dbname=' . DB_NAME . ';'
. 'user=' . DB_USER . ';'
. 'password=' . DB_PASS);
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set error mode to exception
echo “Connected”;
} catch (PDOException $e) {
$fileName = basename($e->getFile(), ".php"); // File that triggers the exception
$lineNumber = $e->getLine(); // Line number that triggers the exception
die("[$fileName][$lineNumber] Database connect failed: " . $e->getMessage() . '<br/>');
}
?>
My PHP submission script: form.php
<?php
require 'connect.php';
$sid = $_POST['sid'];
$firstName = $_POST['fname'];
$preferredName = $_POST['pname'];
$lastName = $_POST['lname'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$inSchool = $_POST['inSchool'];
$gDate = $_POST['gDate'];
$gpa = $_POST['gpa'];
$essay = $_POST['essay'];
$submit = $_POST['submit'];
if ($sid = ''){
$query = 'insert into student(firstname,lastname,prefname,address,city,state,zip,phone,email) values (?,?,?,?,?,?,?,?,?)';
$statement = $dbConn->prepare($query);
$statement->execute([$firstname, $lastname,$preferredname,$address,$city,$state,$zip,$phone,$email]);
}
else{
$query = 'insert into student(firstname,lastname,prefname,address,city,state,zip,phone,email) values (?,?,?,?,?,?,?,?,?)';
$statement = $dbConn->prepare($query);
$statement->execute([$firstname, $lastname,$preferredname,$address,$city,$state,$zip,$phone,$email]);
}
$query = 'select sid from student where firstname = ? and lastname = ? limit 1';
$statement = $dbConn->prepare($query);
$statement->execute([$firstname, $lastname,$preferredname,$address,$city,$state,$zip,$phone,$email]);
$results = $statement->fetch();
echo $results[0];
?>
My HTML Form: Application.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Style.css">
<title>Application</title>
</head>
<body>
<form action="form.php" method="post">
<header>
<img class="logo" src="" alt="logo">
<div>Asterisks Corporation Scholarship Application</div>
</header>
<p class="general">Please fill in all information to apply for the Asterisk's Scholarship.<p>
First Name:
<input type="text" size="15" name="fname" required />
Preferred Name:
<input type="text" size="15" name="pname" >
Last Name:
<input type="text" size="15" name="lname" required />
<p class="newSection">Contact Information</p>
Address:
<input type="text" size="50" name="address" required />
City:
<input type="text" size="15" name="city" required />
State:
<input type="text" size="15" name="state" required />
Zip Code:
<input type="text" size="1" name="zip" placeholder="####" required /><br><br>
Phone Number:
<input type="text" size="10" name="phone" placeholder="(###)-###-###">
Email Address:
<input type="text" size="50" name="email" required />
<p class="newSection">Academic Information</p>
Are you currently enrolled in school?
<input type="checkbox" id="Yes" name="yesBox">
<label for="Yes">Yes</label>
<input type="checkbox" id="No" name="noBox">
<label for="No">No</label><br><br>
What school are you enrolled?
<input type="text" size="50" name="schoolsEnrolled"><br><br>
What is/was your date of Graduation?
<input type="date" name="graduationDate"><br><br>
GPA
<input type="text" size="1" name="gpa">
<p class="newSection">What institutions have you applied?</p>
<input type="text" name="" value="" id="school" name="schoolsApplied">
<button onclick="addToList()" type="button" name="button" id="addButton">Add School</button><br>
<ul id="schoolList"></ul>
<p class="newSection">Please write a small essay as to why you should receive this scholarship and what your plans are after graduation.</p>
<textarea id="essay" style="width: 500px; height: 200px;" alignment="left" onkeyup="wordCounter(),wordsRemaining()" name="essay"></textarea>
<div>
300 Words Minimum & 500 Words Maximum
<div> Word Count: <span id="wordCount">0</span></div>
<div> Words Remaining: <span id="wordsRemaining">0</span></div>
</div>
<p class="newSection">Please confirm each of the following:</p>
<input type="checkbox" id="Transcript" name="transcriptConfirm" required />
<label for="Transcript">I have sent in all of my transcripts</label><br>
<input type="checkbox" id="Schools" name="schoolConfirm" required />
<label for="Schools">All schools that I am considering are in the US</label><br>
<input type="checkbox" id="Awards" name="awardConfirm" required />
<label for="Awards">I understand that the award is $5,000 per year for four years</label><br>
<input type="checkbox" id="Confirm" name="amountConfirm" required />
<label for="Confirm">I have received confirmation that my recommenders have emailed their letters to the Scholarship's Coordinator</label><br><br>
Please type your signature in the text box below: <br><br>
<input type="text" size="20" name="signature" required />
<div><br>
<input type="submit" value ="Submit" name="submit">
<input type="reset" value="Start Over" onclick="MinMax()">
</div>
<script>
function addToList(){
let school= document.getElementById("school").value;
document.getElementById("schoolList").innerHTML += ('<li>'+ school+'</li>');
};
function wordCounter(text){
var count= document.getElementById("wordCount");
var input= document.getElementById("essay");
var text=essay.value.split(' ');
var wordCount = text.length;
count.innerText=wordCount
}
function wordsRemaining(text){
var count= document.getElementById("wordCount");
var input= document.getElementById("essay");
var remaining = document.getElementById("wordsRemaining");
var text=essay.value.split(' ');
var wordCount = text.length;
remaining.innerText=300-wordCount
}
</script>
</form>
</body>
</html>

only can insert first and second value other value cannot insert in database. how to solve this?

<?php
require_once "config.php";
if(isset($_POST['save'])){
$values = array();
for($i=0 ; $i <count($_POST['working']); $i++) {
$values[] = '("' . $_POST['working']['day'][$i] . '","' .
$_POST['working']['status'][$i] . '")'; }
$sql4 = "INSERT INTO working_day(day,status) VALUES " . implode(',',
$values);
$result4=mysqli_query($connection,$sql4);}
?>
<form id="sendform" method="post" action="">
<input type="text" value="Monday" id="day" name="working[day][]" readonly />
<input type="text" value="" id="status" name="working[status][]" />
<input type="text" value="Tuesday" id="day" name="working[day][]" readonly />
<input type="text" value="" id="status" name="working[status][]" />
<input type="text" value="w" id="day" name="working[day][]" readonly />
<input type="text" value="" id="status" name="working[status][]" />
<input type="text" value="T" id="day" name="working[day][]" readonly />
<input type="text" value="" id="status" name="working[status][]" />
<input type="text" value="F" id="day" name="working[day][]" readonly />
<input type="text" value="" id="status" name="working[status][]" />
<input type="text" value="S" id="day" name="working[day][]" readonly />
<input type="text" value="" id="status" name="working[status][]" />
<input type="text" value="S" id="day" name="working[day][]" readonly />
<input type="text" value="" id="status" name="working[status][]" />
<input type="submit" value="Send" name="save" />
</form>
**why this code only can insert first day&status and second day&status into the database ? The for loop count[i] cannot count another value. how to solve this problem? **
Correct way is given below :-
<?php
require_once "config.php";
if(isset($_POST['save'])){
$values = array();
for($i=0 ; $i <count($_POST['working']['day']); $i++) {
$values[] = '("' . $_POST['working']['day'][$i] . '","' . $_POST['working']['status'][$i] . '")';
}
$sql4 = "INSERT INTO working_day(day,status) VALUES " . implode(',', $values);
$result4=mysqli_query($connection,$sql4);
}

trouble with inserting php form data into mysql

i have trouble inserting my with php into one table of mysql, i can insert in any other table but this one here is my code (is a test code)
This is the formulario.php code
<form action="opformulario.php" method="POST">
<br><br>
<input type="text" name="nombre" placeholder="Nombre" />
<br><br>
<input type="text" name="apellido" placeholder="apellido" />
<br><br>
<input type="text" name="correo" placeholder="correo" />
<br><br>
<input type="text" name="nombre2" placeholder="Nombre" />
<br><br>
<input type="text" name="apellido2" placeholder="apellido" />
<br><br>
<input type="date" name="apellido3" placeholder="apellido" />
<input type="submit" value="aceptar" />
and this is the op formulario code
include("conexion.php");
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$correo = $_POST['correo'];
$nombre2 = $_POST['nombre2'];
$apellido2 = $_POST['apellido2'];
$apellido3 = $_POST['apellido3'];
$FechaMySQL = implode( '-', array_reverse( explode( '/', $apellido3 ) ) ) ;
$query = " INSERT INTO cliente (nom_raz,nom_com,tel_cli,cel_cli,email_cli,fecha_reg) VALUES('$nombre','$apellido','$correo','$nombre2','$apellido2','$FechaMySQL')";
$resultado = $conexion->query($query);
if ($resultado){
echo "Succesfull";
}
else{
echo "Error:<br />".mysql_error();
}
this is the table in which i am trying to insert
Mysql 'cliente' table

Edit User page in PHP and PHPMYSQL using Array Drop Down Selection

I would like to ask why every time i try to call programme it doesn't show the results? I'm trying to create edit user page which means i will call back the database but mine doesn't show up.
Here's my Edit User code i have problem with row4
// Retrieve the user's information:
$q = "SELECT first_name, last_name, phone, email , programme FROM users WHERE user_id=$id";
$r = #mysql_query ($q);
if (mysql_num_rows($r) == 1) { // Valid user ID, show the form.
// Get the user's information:
$row = mysql_fetch_array ($r, MYSQL_NUM);
// Create the form:
echo '<div align="center"/div><form action="edit_user.php" method="post">
<p>First Name: <input type="text" name="first_name" size="15" maxlength="15" value="' . $row[0] . '" /></p>
<p>Last Name: <input type="text" name="last_name" size="15" maxlength="30" value="' . $row[1] . '" /></p>
<p>Phone No: <input type="text" name="phone" size="20" maxlength="60" value="' . $row[2] . '" /> </p>
<p>Email Address: <input type="text" name="email" size="20" maxlength="60" value="' . $row[3] . '" /> </p>
<p>Programme: <name="programme" size="20" maxlength="60" value="' . $row[4] . '" /> </p>
<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';
Here's my Registration code because i used drop down so i can't call drop down back in edit user page that include database for programme registered
<?php # Script 3.5 - Registration Form
$page_title = 'Registration Form';
include ('./includes_css/header.html');
?>
<div align="center"><h2>Registration Form</h2>
<form action="register.php" method="post">
<legend>Enter your information in the form below:</legend><br/>
<p><b>First Name:</b> <input type="text" size="21" name="first_name" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>"/></p>
<p><b>Last Name:</b> <input type="text" size="21"name="last_name" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>"/></p>
<p><b>Phone No:</b> <input type="text" size="22"name="phone" value="<?php if (isset($_POST['phone'])) echo $_POST['phone']; ?>"/></p>
<p><b>Email Address:</b> <input type="text" size="18"name="email" /value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"/></p>
<p><b>Programme:</b> <name="programme" value="<?php if (isset($_POST['programme'])) echo $_POST['programme']; ?>"/>
<?php
$programme = array ('null' => 'SELECT','BIMD', 'BSE', 'BCEM', 'BCA', 'DIM', 'DCNET',
'DIT', 'DIA');
// Make the programme pull-down menu.
echo '<select name="programme">';
foreach ($programme as $key => $value) {
echo "<option value=\"$value\">$value</option>\n";
}
echo '</select>';
?>
<div align="center"><input type="submit" name="submit" value="Register" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
I have problem with Edit User page (Program doesn't show up).

ahref tag button insert data into database

I'm working on a form that will insert a data into database but not using button submit. instead, an ahref tag that styled to use as a button. And i can't get the right code for it. here is my code:
html:
<form name="eventform" id="eventform" method="get">
<p> Title: <input type="text" name="title" id="title" required
pattern="[A-Za-z0-9 ,.)(*!?|<>:]{5,80}"
title="Please enter valid title of you event."/></p>
<p> Where: <input type="text" name="place" id="place" required
pattern="[A-Za-z0-9 ,.)(*!?|<>:]{5,100}"/></p>
<p>When: <input type="date" name="date" id="date" required/></p>
<p>People Involved: <input type="text" name="people" id="people" required
pattern="[A-Za-z0-9 ,.)(*!?|<>:]{5,100}"/></p>
<p>Content:</p>
<textarea rows="4" cols="50" required name="content"></textarea>
Cancel
<a href="events.php?/add-event/success" id="btnfinish"
name="btnfinish">Done</a>
</form>
php:
if (isset($_GET['eventform'])) {
$title = $_POST['title'];
$place = $_POST['place'];
$date = $_POST['date'];
$people = $_POST['people'];
$content = $_POST['content'];
$object->addEvent($title, $place, $date, $people, $content);
}
php in other file:
<?php
class Dbother
{
private $host = 'localhost';
private $user = 'root';
private $password = '';
private $dbname = 'pcnl';
private $conn = '';
function connect()
{
$this->conn = mysql_connect(
$this->host, $this->user, $this->password
) or die (mysql_error());
mysql_select_db($this->dbname, $this->conn) or die(mysql_error());
}
//end of connect
function addEvent($title, $place, $date, $people, $content)
{
$sql = "
INSERT INTO tbl_event
VALUES
('$title', '$place', '$date', '$people', '$content', null, null, null)
";
mysql_query($sql) or die (mysql_error());
mysql_close();
}//end of academic
you should just style the input tag
<form name="eventform" id="eventform" method="get" action="events.php?/add-event/success">
<p> Title: <input type="text" name="title" id="title" required pattern="[A-Za-z0-9 ,.)(*!?|<>:]{5,80}" title="Please enter valid title of you event."/></p>
<p> Where: <input type="text" name="place" id="place" required pattern="[A-Za-z0-9 ,.)(*!?|<>:]{5,100}"/></p>
<p>When: <input type="date" name="date" id="date" required /></p>
<p>People Involved: <input type="text" name="people" id="people" required pattern="[A-Za-z0-9 ,.)(*!?|<>:]{5,100}"/></p>
<p>Content:</p>
<textarea rows="4" cols="50" required name="content"></textarea>
Cancel
<input id="btnfinish" type="submit" value="Done">
</form>
PS: you could submit form programtically but you don't have to

Categories