Avatar of Wayeel Cade
Wayeel Cade
 asked on

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);
HTMLDatabasesPHP

Avatar of undefined
Last Comment
Wayeel Cade

8/22/2022 - Mon
SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Wayeel Cade

ASKER
yes Sir.. How can i do that?
SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Wayeel Cade

ASKER
$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.
SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Wayeel Cade

ASKER
Parse error: syntax error, unexpected ')', expecting '(' in C:\wamp64\www\april\insert.php on line 15

//line 15
foreach($level as $idx => level_value)
Your help has saved me hundreds of hours of internet surfing.
fblack61
Wayeel Cade

ASKER
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.
SOLUTION
mohan singh

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Wayeel Cade

ASKER
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
mohan singh

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
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Wayeel Cade

ASKER
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);
}
?>
mohan singh

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

Julian Hansen

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

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Wayeel Cade

ASKER
can you do one that inserts data into the DB sir?
Julian Hansen

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.
ASKER CERTIFIED SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Wayeel Cade

ASKER
finally solved it.
I just can't appreciate you guys enough..Thanks all for your great help.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
gr8gonzo

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.
Wayeel Cade

ASKER
perfectly working for me Mr. gr8gronzo.. am following your way..
Julian Hansen

@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,
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
gr8gonzo

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. :)
Julian Hansen

@Gr8gonzo,

Ok - as it turns out asker saw no value in my comment anyway so moot point I guess.
gr8gonzo

-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.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Wayeel Cade

ASKER
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.