PHP Code not inserting into MySQL

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. Another question is how do I convert the dates from 00-00-0000 to 0000-00-00 so it can be inputted into the database correctly.

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["jigowatt"]["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);

	  
	}
}
?>

Open in new window


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['jigowatt']['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>	

Open in new window

Genesis5150Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Genesis5150Author Commented:
Actually forget the second question I found out it is date("d-m-Y", ) but that won't be used until I echo/print the date. It has to be inserted as 00-00-0000 into the MySQL. Still can't figure out the first part.
0
F PCommented:
You're using mysqli when you go to execute the mysql connection object.
0
F PCommented:
$bd = mysql_connect("localhost","####_####","####");
if (!$bd){die('Could not connect: ' . mysql_error());}
      
      mysql_select_db("####",$bd);
      
      $username = $_SESSION["jigowatt"]["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)){  //  <--- riiiight there it is 

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Dave BaldwinFixer of ProblemsCommented:
Frank is right, you can not mix 'mysql' and 'mysqli' functions.  They are from completely different libraries and do not work together.
0
Ray PaseurCommented:
This article will show you most of the basics of using MySQLi or PDO in a consistent and successful manner.  Do not use MySQL functions ever - it's the 1995 way of doing things and PHP is removing those functions from the language, so just don't go there at all.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Date/time values in are described in this article.  Executive summary: You really want to understand and use the ISO-8601 format for all internal representations, all the time.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
0
Ray PaseurCommented:
Going forward, you might want to learn about the SSCCE.  It's the best thing you can do when you need to get a good answer to a technical question.  In this question we have a mashup of HTML, CSS and PHP code that is hard to read and understand.  The more you can strip out of that, the better.  If you can reduce the question and code samples to just the part that is not doing what you want, you will save a lot of time.
0
Genesis5150Author Commented:
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);
		}	  
	}
}
?>

Open in new window


But now I'm getting this error:
Notice: Undefined variable: doNotSubmit in C:\xampp\htdocs\user\booking\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
0
Ray PaseurCommented:
Try adding this statement right after the error_reporting() statement.
$doNotSubmit = FALSE;

Open in new window

And please, please, please give yourself a chance to get some structured learning about PHP.  Copying and pasting without understanding the code is not going to get you very far.  I understand if you do not want to learn PHP -- most people do not want to learn PHP.  But if you want to write PHP programs, you have to learn PHP.  Or you have to hire a programmer who already knows PHP.

For the SQL syntax error, I'm not sure what's wrong.  You can use var_dump() to print out the fully-resolved query string.  Maybe the syntax error will be easy to spot.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Genesis5150Author Commented:
Thank you Ray and yes I will read up on PHP coding. I picked up Murach's PHP and MySQL book and stated reading it 2 weeks ago. Also the syntax error was too many ")"s Changed 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())");
0
F PCommented:
What's handy and cleaner is to use double quotes like 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() )");

Open in new window


... and also remember -> when in doubt, echo it out!

$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() )");

echo $insert_row; // take this output and run it on the MYSQL command line or through another query utility.. I like HeidiSQL and SequelPro depending on mac or windows.
exit;

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

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.