0

i need to insert list of string into mysql, so how do i do it?

<?php
require "connection.php";

$res_rname= "Baler";
$res_per_name= "ken";
$res_id= "102";

$datess="2018-08-16, 2018-08-17, 2018-08-17";
$mydate=explode(',',$datess);
$dates = $mydate;


$sql_query = "Insert into res_event_table ( res_id, res_check_in_out, 
res_room_name, res_name) values ( '$res_id','$val', '$res_rname', 
'$res_per_name')";
if($dates>0)
{
    foreach($dates as $val){
        $result = mysqli_query($conn ,$sql_query);
            if (!$result){
            echo "failed" .mysqli_connect_error;
            }else{
            echo "Reservation Success";
       }
    }
 }

?>

this is how far i get, it insert the other value but the list of date string leaves empty space in my database i read this but it doesnt work for me i dont know why.

1
  • echo "failed" .mysqli_connect_error; that isn't the correct error checking method. That's for connection, not for querying. Commented Sep 8, 2018 at 12:29

1 Answer 1

0

You are doing a lots of simple mistakes, correct code is as below,

<?php
require "connection.php";

$res_rname= "Baler";
$res_per_name= "ken";
$res_id= "102";

$datess="2018-08-16, 2018-08-17, 2018-08-17";
$mydate=explode(',',$datess);
$dates = $mydate;  // No need to create a separate variable but ok for now 


if(count($dates)>0)
{
    foreach($dates as $val){
        $sql_query = "Insert into res_event_table ( res_id, res_check_in_out, 
res_room_name, res_name) values ( '$res_id','$val', '$res_rname', 
'$res_per_name')";

        $result = mysqli_query($conn ,$sql_query);
            if (!$result){
            echo "failed" .mysqli_connect_error;
            }else{
            echo "Reservation Success";
       }
    }
 }

?>
Sign up to request clarification or add additional context in comments.

5 Comments

Your answer is wide open to SQL Injection Attack Even if you are escaping inputs, its not safe! Use prepared parameterized statements in either the MYSQLI_ or PDO API's
@RiggsFolly I know but knowing ken's knowledge it's ok for him.
@ken you can upvote answer clicking on the ^ button left of the answer.
i dont have enough reputation to upvote but i appreciate your help and i will upvote it if have enough rep. thanks for your help @bhagwanparge
you should escape strings in case of input is coming from outside of this code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.