not able to connect to database

I  have a html form which is connected to be php file and inserts data into sql.
my issue is i want to submit multiple text boxes with the same name and insert into database.
i don't know how to loop it through.

html file
<table>
<form action="insert.php" method="post"  >
<tr>
    <th>Time</th>
    <th>Level</th>
    <th>Room</th>
  </tr>
 
 <tr>       
<td>
 <select id="drop" name="time">
               <option value = "8:30-12:30">8:30-12:30</option>
               <option value = "12:45-1:45">12:45-1:45</option>
               <option value = "2:00-6:00">2:00-6:00</option>
             </select>
 <td> <input type="text" name="level" id="level">
 <td><input type="text" name="room" id="Room">
</tr>
 <tr>  
<td>
 <td> <input type="text" name="level" id="level">
 <td><input type="text" name="room" id="Room">
</tr>
<tr>
      <td><input type="submit" name="submit" value="Submit form"></td>
   </tr>
</form>
</table>

insert.php
$time = mysqli_real_escape_string($link, $_REQUEST['time']);
$level = mysqli_real_escape_string($link, $_REQUEST['level']);
$room = mysqli_real_escape_string($link, $_REQUEST['room']);

$sql = "INSERT INTO april (time, level, room) VALUES ('$time', '$level', '$room')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// close connection
mysqli_close($link);
Wayeel CadeAsked:
Who is Participating?
 
gr8gonzoConsultantCommented:
Wayeel, you almost had it correct with my code. The error you mentioned:
Parse error: syntax error, unexpected ')', expecting '(' in C:\wamp64\www\april\insert.php on line 15

//line 15
foreach($level as $idx => level_value)

...is because you missed a $ before "level_value":
foreach($level as $idx => $level_value)
1
 
gr8gonzoConsultantCommented:
Are you saying you want your HTML form to collect multiple records and submit them in one post, and you want the PHP file to handle the multiple inserts?
0
 
Wayeel CadeAuthor Commented:
yes Sir.. How can i do that?
0
Network Scalability - Handle Complex Environments

Monitor your entire network from a single platform. Free 30 Day Trial Now!

 
gr8gonzoConsultantCommented:
Use square brackets at the end of your input names:

<td> <input type="text" name="level[0]" id="level">
 <td><input type="text" name="room[0]" id="Room">
...
<td> <input type="text" name="level[1]" id="level">
 <td><input type="text" name="room[1]" id="Room">
...
<td> <input type="text" name="level[2]" id="level">
 <td><input type="text" name="room[2]" id="Room">
...etc...

You can also just use empty square brackets [] but I find it good practice to number the indexes yourself.

When your form is submitted, level and room will be arrays that you can loop through:

$level = mysqli_real_escape_string($link, $_REQUEST['level']);
$room = mysqli_real_escape_string($link, $_REQUEST['room']);

foreach($level as $idx => level_value)
{
  $room_value = $room[$idx];

  ... Do your insert query here with $level_value and $room_value...
}
0
 
gr8gonzoConsultantCommented:
On my phone I can't edit my comment but you should be calling the escape string on $room_value and $level_value instead of on $room and $level since those will now be arrays.
0
 
Wayeel CadeAuthor Commented:
$time = mysqli_real_escape_string($link, $_REQUEST['time']);
$level = mysqli_real_escape_string($link, $_REQUEST['level']);
$room = mysqli_real_escape_string($link, $_REQUEST['room']);

foreach($level as $idx => level_value)
{
  $room_value = $room[$idx];
 
$sql = "INSERT INTO april (time, level, room) VALUES ('$time', '$level', '$room')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// close connection
mysqli_close($link);

this is what i did and it giving me errors.. am really sorry am totally new to this..thanks in advance sir.
0
 
gr8gonzoConsultantCommented:
$time = mysqli_real_escape_string($link, $_REQUEST['time']);
$level =  $_REQUEST['level'];
$room =  $_REQUEST['room'];

foreach($level as $idx => level_value)
{
  $room_value = mysqli_real_escape_string($link, $room[$idx]);
  $level_value = mysqli_real_escape_string($link, $level_value);

$sql = "INSERT INTO april (time, level, room) VALUES ('$time', '$level_value', '$room_value')";
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// close connection
mysqli_close($link);
0
 
Wayeel CadeAuthor Commented:
Parse error: syntax error, unexpected ')', expecting '(' in C:\wamp64\www\april\insert.php on line 15

//line 15
foreach($level as $idx => level_value)
0
 
Wayeel CadeAuthor Commented:
This is being helpful and I appreciate it beyond words.
Do you know what might be the cause for that parse error?
Thanks a lot.
0
 
mohan singhWeb developerCommented:
If you want to insert multiple record in one submit button so do like this
// this is your html content  put your all name into array format  
<input type="text" name="user[]">
<input type="text" name="mobile[]">
<input type="text" name="user[]">
<input type="text" name="mobile[]">
<input type='submit' name='submit'>

Open in new window


<?php
if(isset($_POST['submit'])){
for($i=0; $i<count($_POST['user']); $i++){
if(trim($_POST["user"][$i] && $_POST['mobile'] ! = ''){
$sql = mysqli_query($conn, "INSERT INTO TableName(user,mobile) VALUES ('".$_POST['user'][$i]."','".$_POST['mobile'][$i]."')";
 
}
}
}
?>

Open in new window

// Sure it will work
0
 
Wayeel CadeAuthor Commented:
mr Mohan I tried your solution am having parse error and on  if(trim($_POST["user"][$i] && $_POST['mobile'] ! = '')

Parse error: syntax error, unexpected ';' in C:\wamp64\www\demo\insert.php on line 15
0
 
mohan singhWeb developerCommented:
Hi@Wayeel Cade
Can you show me your fully insert query
because my solution is correct
and I think you missed some or put extra semi coma


THNX
0
 
Wayeel CadeAuthor Commented:
it's here Sir
<?php

$link = mysqli_connect("localhost", "root", "", "demo");
 
// Check connection
if($link === false){
    die("ERROR: Could not connect. " . mysqli_connect_error());
}


if(isset($_POST['submit'])){
for($i=0; $i<count($_POST['time']); $i++){
if(trim($_POST["time"][$i] && $_POST['level']&& $_POST['room'] ! = ''){
$sql = mysqli_query($conn, "INSERT INTO april(time,level,room) VALUES ('".$_POST['time'][$i]."','".$_POST['level'][$i]."','".$_POST['room'][$i]."')";
 
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
 
// close connection
mysqli_close($link);
}
?>
0
 
mohan singhWeb developerCommented:
Please answer your code in code bracket ok

Can you tell me what is $conn in your query
$sql = mysqli_query($conn, "INSERT INTO april(time,level,room) VALUES ('".$_POST['time'][$i]."','".$_POST['level'][$i]."','".$_POST['room'][$i]."')";

Open in new window

$conn is connection string which is just example which I just told you

and you are using
 $_POST['time']

Open in new window

is this  field multiple or not

remove this content and change $conn with your connection string  then submit your query  
if(mysqli_query($link, $sql)){
    echo "Records added successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

Open in new window

1
 
Julian HansenCommented:
Some comments on your HTML
1. ID's must be unique - you have level and room used more than once
2. Your markup is invalid - you have your <form> inside your <table> element - move the table inside the form
3. Using a table for layout is considered bad practice - rather use div's - especially if you are targeting mobile.

Then to use multiple inputs with the same name use the approach already described by Gr8gonzon above - name arrays - I would use the non-indexed version as it is easier to extend without remembering to update the indices.
Here is the corrected code with changes
<form action="t3096.php" method="post"  >
<table>
  <tr>
	<th>Time</th>
	<th>Level</th>
	<th>Room</th>
  </tr>

  <tr>       
	<td>
	<select id="drop" name="time">
	  <option value = "8:30-12:30">8:30-12:30</option>
	  <option value = "12:45-1:45">12:45-1:45</option>
	  <option value = "2:00-6:00">2:00-6:00</option>
	</select>
	<td> <input type="text" name="level[]" id="level_1">
	<td><input type="text" name="room[]" id="Room_1">
  </tr>
  <tr>  
  <td>
	<td> <input type="text" name="level[]" id="level_2">
	<td><input type="text" name="room[]" id="Room_2">
  </tr>
  <tr>
	<td><input type="submit" name="submit" value="Submit form"></td>
  </tr>
</table>
</form>

Open in new window

Here is the PHP
<?php
// Simulate db connection
$proc = true;
require('connection.php');
$link = $conn;

// Get our POST variables cleanly
$time = isset($_POST['time']) ? $_POST['time'] : false;
$level = isset($_POST['level']) ? $_POST['level'] : false;
$room = isset($_POST['room']) ? $_POST['room'] : false;

// Check for valid input 
// level and room both arrays and have the same number of elements
if ($time && is_array($level) && is_array($room) && count($level) == count($room)) {

  // either clean or validate time
  $time = preg_replace('/[^\d-:]/','', $time);
  
  // We use a batch insert to insert our values. One query with multiple values
  // this is more efficient than running an individual query for each insert
  $query = <<< QUERY
INSERT INTO april(time,level,room) VALUES 
QUERY;
  foreach($level as $i => $l) {
    $lvl = mysqli_real_escape_string($link, $[url="http://www.marcorpsa.com/ee/t3096.html"][/url]l);
    $rm =  mysqli_real_escape_string($link, $room[$i]);
    $query .= <<< VALUES
  ('{$time}','{$lvl}','{$rm}'),
VALUES;
  }
  $query = trim($query, ',');
  mysqli_query($link, $query);
}
else {
 // handle invalid input here
  echo "Invlalid inputs found";
}

Open in new window

You can see a working sample here
Note: the sample above outputs the final SQL query - it does not insert data into the DB

EDIT
Fixed the preg_match to include the pattern delimiters / /
  $time = preg_replace('/[^\d-:]/','', $time);

Open in new window

1
 
Wayeel CadeAuthor Commented:
can you do one that inserts data into the DB sir?
0
 
Julian HansenCommented:
The code I posted does do an insert - look at line 32.

It is only the online sample that does not and I am not going to implement a DB insert in the online sample as it is not necessary - the code demonstrates clearly what needs to be done and the answer here provides the code on how to do it.

You have everything you need to proceed.
1
 
Wayeel CadeAuthor Commented:
finally solved it.
I just can't appreciate you guys enough..Thanks all for your great help.
0
 
gr8gonzoConsultantCommented:
I have to disagree with Julian on one thing:
I would use the non-indexed version as it is easier to extend without remembering to update the indices.

I used to do this, but it's a bad practice. You are just starting out, so this might not make a lot of sense yet, so let's start with explaining how the square brackets work.

Basically, in PHP, the square brackets mean that you're specifying an array index to work with. For example, this created an array called $myArray and then adds two elements to it:
<?php
$myArray = array();
$myArray[0] = "hello";
$myArray[1] = "world";

Open in new window


This code products exactly the same result:
<?php
$myArray = array();
$myArray[] = "hello";
$myArray[] = "world";

Open in new window


The reason it produces the same result is that empty square brackets are a PHP shortcut that means "the next index number", so when the array is completely empty, the next index number would 0, so [] would be the same as [0]. Then the next number after 0 is 1, so when you used [] again, it would be the same as [1]. Then the next [] would be 2, and then the next use of [] would be 3, and so on.

This works great when your arrays indexes always start at 0 and always increment by 1. However, if you wanted your array to be something like this:
<?php
$myArray = array();
$myArray[10] = "hello";
$myArray[20] = "world";

Open in new window


...then using [] in this scenario would not produce the same result, because you're specifying indexes that don't go increment by 1 each time.

When you use square brackets in HTML inputs, PHP is using those the same way to convert the HTML elements into inputs, so:
<input type="text" name="name[]">
<input type="text" name="name[]">

Open in new window

...will be like writing this code:
$_REQUEST = array();
$_REQUEST["name"] = array();
$_REQUEST["name"][] = "Value of the first name input";
$_REQUEST["name"][] = "Value of the second name input";

Open in new window


Now, the problem with this is that if you get used to using this approach, you'll eventually use it in a form that has checkboxes. HTML checkboxes act a little different in the sense that they are not submitted if they are not checked, which means that if you are just using empty square brackets [], you'll have mismatched data.

For example, let's say you are using empty square brackets and you have this form:
<input type="text" name="first_name[]">
<input type="text" name="last_name[]">
<input type="checkbox" name="has_a_car[]">

<input type="text" name="first_name[]">
<input type="text" name="last_name[]">
<input type="checkbox" name="has_a_car[]">

<input type="text" name="first_name[]">
<input type="text" name="last_name[]">
<input type="checkbox" name="has_a_car[]">

Now let's say you fill out the form and only the second person has "has_a_car[]" checked. The result will be:

$_REQUEST["first_name"][0] = "First person's first_name";
$_REQUEST["last_name"][0] = "First persons's last_name";
$_REQUEST["has_a_car"][0] = "Second persons's has_a_car";

$_REQUEST["first_name"][1] = "Second person's first_name";
$_REQUEST["last_name"][1] = "Second persons's last_name";

$_REQUEST["first_name"][2] = "Third person's first_name";
$_REQUEST["last_name"][2] = "Third persons's last_name";

This is because when you don't check has_a_car for the first and third persons, the input is not submitted at all, so you will ONLY get one "has_a_car" and it will be for the second person, but using the empty square brackets shortcut will start the next index at 0, which is the index used by the first person's inputs.

If you specify your indexes, however:
<input type="text" name="first_name[0]">
<input type="text" name="last_name[0]">
<input type="checkbox" name="has_a_car[0]">

<input type="text" name="first_name[1]">
<input type="text" name="last_name[1]">
<input type="checkbox" name="has_a_car[1]">

<input type="text" name="first_name[2]">
<input type="text" name="last_name[2]">
<input type="checkbox" name="has_a_car[2]">

...then you will STILL only get one checkbox input, but since you're specifying your indexes, the index for your checkbox will still correlate to the second person.

$_REQUEST["first_name"][0] = "First person's first_name";
$_REQUEST["last_name"][0] = "First persons's last_name";

$_REQUEST["first_name"][1] = "Second person's first_name";
$_REQUEST["last_name"][1] = "Second persons's last_name";
$_REQUEST["has_a_car"][1] = "Second persons's has_a_car";

$_REQUEST["first_name"][2] = "Third person's first_name";
$_REQUEST["last_name"][2] = "Third persons's last_name";

I know this is probably a little advanced at this point, but it might make sense later on.
1
 
Wayeel CadeAuthor Commented:
perfectly working for me Mr. gr8gronzo.. am following your way..
0
 
Julian HansenCommented:
@Gr8gonzo,

Checkboxes are a special case and I agree that using defined indices is the way to go - but this form does not use check boxes. It is much of a muchness I shared something I have found through experience - I have tried both methods and found - for the coding I do an automatic index works much better for me.

Each to his own,
1
 
gr8gonzoConsultantCommented:
Yep, I just wanted to call that out since the OP is just starting out. I think shortcuts are great once you have a better understanding of when to use and not use them. That's why I had said early on that it was a good practice to get used to using the user-defined approach for now. :)
1
 
Julian HansenCommented:
@Gr8gonzo,

Ok - as it turns out asker saw no value in my comment anyway so moot point I guess.
1
 
gr8gonzoConsultantCommented:
-shrug- people who are new to PHP just have to take things in smaller bites. He was still trying to figure out HTML forms and I figured you might have lost him with the regexes. Hopefully he will come back to this later on and get more value out of your comments, regardless of points.
1
 
Wayeel CadeAuthor Commented:
Mr @Julian Hansen am sorry if you felt that way as Mr Gr8gonzo pointed out am a starter that's why I couldn't understand it.
But I really appreciate the time and the effort.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.