Jump to content

PHP Code not inserting into MySQL


Genesis5150
Go to solution Solved by scootstah,

Recommended Posts

Could someone please help me. I can't figure out why this code is not inserting into the database. All the values are filled in.

Thanks

<?php
error_reporting(E_ALL); 
if(isset($_POST['submit'])) 
{

$fielderror = "";
    if( $_POST["percent"] == "" || $_POST["spots"] == "" || $_POST["cancel"]  == "" || $_POST["start"]  == "" || $_POST["finish"]  == ""){
      //$errorTrace .= "after <br>";
    $fielderror="Please fill the fields annotated with an asterisk<br>";
    $doNotSubmit = true;
    }
     if( !is_numeric($_POST["percent"]) /*!(preg_match('#^\d+(\.(\d{2}))?$#',($_POST["amount"])))*/ ){
      $fielderror="Only Numbers In The Deposit Field";
      $doNotSubmit = true;
    }
    if( $_POST['spots'] != "" ){
         if (!is_numeric($_POST['spots'])) {
           $fielderror .="Only Numbers In The Spots Field";
           $doNotSubmit = true;
         }
    }
	if( $_POST['cancel'] != "" ){
         if (!is_numeric($_POST['cancel'])) {
           $fielderror .="Only Numbers In The Cancelation Field";
           $doNotSubmit = true;
         }
    }
	
	if( $doNotSubmit == false ) {   

$bd = mysql_connect("localhost","####_####","####");
if (!$bd){die('Could not connect: ' . mysql_error());}
      
      mysql_select_db("####",$bd);
      
      $username = $_SESSION["class"]["username"];
	  $sql = "INSERT INTO bookings (username, title, percent, spots, mini, cancel, start, finish, date_created) VALUES ('".$username."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['percent'])."', '".mysql_real_escape_string($_POST['spots'])."', '".mysql_real_escape_string($_POST['mini'])."', '".mysql_real_escape_string($_POST['cancel'])."', '".mysql_real_escape_string($_POST['start'])."', '".mysql_real_escape_string($_POST['finish'])."', NOW(), ')";

if(mysqli_query($bd, $sql)){

    echo "Records added successfully.";

} else{

    echo "ERROR: Could not able to execute $sql. " . mysqli_error($bd);

}

 

// Close connection

mysqli_close($link);

	  
	}
}
?>

The Form:

 

<form action="index.php" id="dates" method="post" name="dates" class="sky-form" onSubmit="return Blank_TextField_Validator()" enctype='multipart/form-data' />
        		
				<div class="row">					
				<fieldset>	
                <section class="col col-6">
                <span style="background-color:#0000cd; font-size:16px; color:white; padding:5px;">Select Unit</span>
                    <label class="select">                    	 
                        <?php 
						$sql = "SELECT * FROM units WHERE `username` = '".$_SESSION['class']['username']."'ORDER BY date_created DESC";
						$result = mysql_query($sql);
							echo "<select name='title'>";
							while ($row = mysql_fetch_array($result)) {
								echo "<option value='" . $row['title'] . "'>" . $row['title'] . "</option>";
							}
							echo "</select>";
							?>
                    		<i></i>
						</label>
					</section>	                    
                    </div>
                    
                    <div class="row">					
						<section class="col col-3">
                        <span style="background-color:#0000cd; font-size:16px; color:white; padding:5px;">*Percentage of Deposit</span>
							<label class="input">
                            	<i class="icon-prepend fa fa-bar-chart-o"></i>
								<input type="text" name="percent" id="percent" placeholder="100%" value="<?php print isset($_POST['percent']) ? strip_tags($_POST['percent']) : ""; ?>">
							</label>
						</section>	                    
                    </div>
                    
                    
                    <div class="row">					
						<section class="col col-2">
                        <span style="background-color:#0000cd; font-size:16px; color:white; padding:5px;">*How Many Spots?</span> 
							<label class="input">
                            	<i class="icon-prepend fa fa-bed"></i>
								<input type="text" name="spots" id="spots" placeholder="Available Spots" value="<?php print isset($_POST['spots']) ? strip_tags($_POST['spots']) : ""; ?>">
							</label>
						</section>
                        <section class="col col-2">
                        <span style="background-color:#0000cd; font-size:16px; color:white; padding:5px;">*Minimum Days?</span> 
							<label class="input">
                            	<i class="icon-prepend fa fa-calendar-o"></i>
								<input type="mini" name="mini" id="mini" placeholder="Minimum" value="<?php print isset($_POST['mini']) ? strip_tags($_POST['mini']) : ""; ?>">
							</label>
						</section>
                       	<section class="col col-4">
                        <span style="background-color:#0000cd; font-size:16px; color:white; padding:5px;">*How Many Days Before Cancellation?</span> 
							<label class="input">
                            	<i class="icon-prepend fa fa-times"></i>
								<input type="text" name="cancel" id="cancel" placeholder="Days Before Cancellation" value="<?php print isset($_POST['cancel']) ? strip_tags($_POST['cancel']) : ""; ?>">
							</label>
						</section> 		                    
                    </div>
                    			
						
					<div class="row">	
						<section class="col col-2">
                        <span style="background-color:#0000cd; font-size:16px; color:white; padding:5px;">*Select Start Date</span>
							<label class="input">
                            <i class="icon-prepend fa fa-calendar"></i>
								<input type="text" name="start" id="start" placeholder="Start date" value="<?php print isset($_POST['start']) ? strip_tags($_POST['start']) : ""; ?>">
							</label>
						</section>
						<section class="col col-2">
                        <span style="background-color:#0000cd; font-size:16px; color:white; padding:5px;">*Select Finish Date</span>
							<label class="input">
								<i class="icon-prepend fa fa-calendar"></i>
								<input type="text" name="finish" id="finish" placeholder="Finish date" value="<?php print isset($_POST['finish']) ? strip_tags($_POST['finish']) : ""; ?>">
							</label>
						</section>
					</div>					
				</fieldset>
					
				
				<footer>
					<button input name='submit' type='submit' value='submit' class="button">Submit</button>
				</footer>
			</form>	
Edited by Genesis5150
Link to comment
Share on other sites

Ok so I changed my code to fit MySQLi to this:

error_reporting(E_ALL); 

if(isset($_POST['submit'])) 
{

$fielderror = "";
    if( $_POST["percent"] == "" || $_POST["spots"] == "" || $_POST["cancel"]  == "" || $_POST["mini"] == "" || $_POST["start"]  == "" || $_POST["finish"]  == ""){
    $fielderror="Please fill the fields annotated with an asterisk<br>";
    $doNotSubmit = true;
    }
     if( !is_numeric($_POST["percent"]) /*!(preg_match('#^\d+(\.(\d{2}))?$#',($_POST["amount"])))*/ ){
      $fielderror="Only Numbers In The Deposit Field";
      $doNotSubmit = true;
    }
    if( $_POST['spots'] != "" ){
         if (!is_numeric($_POST['spots'])) {
           $fielderror .="Only Numbers In The Spots Field";
           $doNotSubmit = true;
         }
    }
	if( $_POST['cancel'] != "" ){
         if (!is_numeric($_POST['cancel'])) {
           $fielderror .="Only Numbers In The Cancelation Field";
           $doNotSubmit = true;
         }
	}
	if( $_POST['mini'] != "" ){
         if (!is_numeric($_POST['mini'])) {
           $fielderror .="Only Numbers In The Minimum Stay Field";
           $doNotSubmit = true;
         }
    }
	
	if( $doNotSubmit == false ) {   

$dbhost = 'localhost';
$dbuser = '####';
$dbpass = '####';
$dbname = '####'; // Database name 
$tbl_name = 'bookings'; // Table name

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

$username = $_SESSION["class"]["username"];

// check connection
if ($conn->connect_error) {
  trigger_error('Database connection failed: '  . $conn->connect_error, E_USER_ERROR);
	}
$title = mysqli_real_escape_string($conn, $_POST['title']);
$percent = mysqli_real_escape_string($conn, $_POST['percent']);
$spots = mysqli_real_escape_string($conn, $_POST['spots']);
$mini = mysqli_real_escape_string($conn, $_POST['mini']);
$cancel = mysqli_real_escape_string($conn, $_POST['cancel']);
$start = mysqli_real_escape_string($conn, $_POST['start']);
$finish = mysqli_real_escape_string($conn, $_POST['finish']);
      
$insert_row = $conn->query("INSERT INTO bookings (username, title, percent, spots, mini, cancel, start, finish, date_created) VALUES ('".$username."','".$title."','".$percent."','".$spots."','".$mini."','".$cancel."','".$start."','".$finish."', NOW(), ')");

		if($insert_row){
				print 'Success! <br />';
			}else{
				die('Error This happen : ('. $conn->errno .') '. $conn->error);
		}	  
	}
}
?>

But now I'm getting this error:
Notice: Undefined variable: doNotSubmit in C:\xampp\htdocs\user\booki

ng\index.php on line 38

Error This happen : (1064) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '')' at line 1
Link to comment
Share on other sites

  • Solution

Please use proper code indentation, so that your code is readable.

 

<?php

error_reporting(E_ALL);

if (isset($_POST['submit'])) {

    $fielderror = "";
    if ($_POST["percent"] == "" || $_POST["spots"] == "" || $_POST["cancel"] == "" || $_POST["mini"] == "" || $_POST["start"] == "" || $_POST["finish"] == "") {
        $fielderror = "Please fill the fields annotated with an asterisk<br>";
        $doNotSubmit = true;
    }
    if (!is_numeric($_POST["percent"]) /*!(preg_match('#^\d+(\.(\d{2}))?$#',($_POST["amount"])))*/) {
        $fielderror = "Only Numbers In The Deposit Field";
        $doNotSubmit = true;
    }
    if ($_POST['spots'] != "") {
        if (!is_numeric($_POST['spots'])) {
            $fielderror .= "Only Numbers In The Spots Field";
            $doNotSubmit = true;
        }
    }
    if ($_POST['cancel'] != "") {
        if (!is_numeric($_POST['cancel'])) {
            $fielderror .= "Only Numbers In The Cancelation Field";
            $doNotSubmit = true;
        }
    }
    if ($_POST['mini'] != "") {
        if (!is_numeric($_POST['mini'])) {
            $fielderror .= "Only Numbers In The Minimum Stay Field";
            $doNotSubmit = true;
        }
    }

    if ($doNotSubmit == false) {

        $dbhost = 'localhost';
        $dbuser = '####';
        $dbpass = '####';
        $dbname = '####'; // Database name
        $tbl_name = 'bookings'; // Table name

        $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

        $username = $_SESSION["class"]["username"];

// check connection
        if ($conn->connect_error) {
            trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
        }
        $title = mysqli_real_escape_string($conn, $_POST['title']);
        $percent = mysqli_real_escape_string($conn, $_POST['percent']);
        $spots = mysqli_real_escape_string($conn, $_POST['spots']);
        $mini = mysqli_real_escape_string($conn, $_POST['mini']);
        $cancel = mysqli_real_escape_string($conn, $_POST['cancel']);
        $start = mysqli_real_escape_string($conn, $_POST['start']);
        $finish = mysqli_real_escape_string($conn, $_POST['finish']);

        $insert_row = $conn->query("INSERT INTO bookings (username, title, percent, spots, mini, cancel, start, finish, date_created) VALUES ('" . $username . "','" . $title . "','" . $percent . "','" . $spots . "','" . $mini . "','" . $cancel . "','" . $start . "','" . $finish . "', NOW(), ')");

        if ($insert_row) {
            print 'Success! <br />';
        } else {
            die('Error This happen : (' . $conn->errno . ') ' . $conn->error);
        }
    }
}
Your first problem is that you have only defined $doNotSubmit if one of the conditionals matches. So, you need to define a default for it.

 

if (isset($_POST['submit'])) {
    $doNotSubmit = false;
Your other problem is that you have a syntax error at the end of your query.

NOW(), ')");
Link to comment
Share on other sites

Thanks everyone for the help also the syantax error was fixed by changing it to this:
 

$insert_row = $conn->query("INSERT INTO bookings (username, title, percent, spots, mini, cancel, start, finish, date_created) VALUES ('".$username."','".$title."','".$percent."','".$spots."','".$mini."','".$cancel."','".$start."','".$finish."', NOW())");

Alo thanks jcbones!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.