Jump to content

I have trouble sending data to database using PDO, any help would be appreciated.


Go to solution Solved by vet911,

Recommended Posts

I'm having trouble sending data to database, nothing apprear in table and no error messages. Below is the file I'm using.

<?php
error_reporting(E_ALL);
        ini_set('display_errors', '1');
		
if(isset($_POST["submit"])){
$hostname='xxxxxx';
$username='xxxxxx';
$password='xxxx';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=dblogin",$username,$password);

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
 
$sql = "INSERT INTO register (fname, lname, address, city, state, zip, phone, large, lsize, lmatl, medium, msize, mmatl, small, ssize, smatl, desc1, desc2, desc3)
VALUES ('".$_POST["fname"]."','".$_POST["lname"]."','".$_POST["address"]."','".$_POST["city"]."','".$_POST["state"]."','".$_POST["zip"]."','".$_POST["phone"]."','".$_POST["large"]."','".$_POST["lsize"]."','".$_POST["lmatl"]."','".$_POST["medium"]."','".$_POST["msize"]."','".$_POST["mmatl"]."','".$_POST["small"]."','".$_POST["ssize"]."','".$_POST["smatl"]."','".$_POST["desc1"]."','".$_POST["desc2"]."','".$_POST["desc3"]."')";


if ($dbh->query($sql)) {
     echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} 
else{
     echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}

    $dbh = null;
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

}
?>

For starters you never insert user supplied data directly into the database. You are using PDO incorrectly. You need to use parameterized queries.

 

Since you didn't post your form code it is impossible to tell if submit is even properly set. You should not be depending on the status of a button name to be submitted in order for your code to work. I am on my phone at the moment so I cannot post you the proper links to look at.

Edited by benanamen

I have enclosed all the form below, this worked fine on localhost that's why I was surprised it didn't work.

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="bootstrap/css/bootstrap-theme.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
<link rel="stylesheet" href="style.css" type="text/css"  />
<link rel="stylesheet" href="style_test.css" type="text/css"  />
<title></title>
</head>

<body>

<nav class="navbar navbar-default navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="http://www.php">About</a></li>
            <li><a href="http://guidelines.php">Guidelines</a></li>
            <!--<li><a href="http://home.php">Back</a></li> -->
	  </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="logout.php?logout=true"><span class="glyphicon glyphicon-log-out"></span> Log Out</a></li>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>


    <div class="clearfix"></div>
    	
    
<!-- <div class="container-fluid" style="margin-top:80px;"> 
	
<div class="container"> -->

<div class="container-fluid text-center" style="margin-top:80px;">
    
  <div class="row content">
    <div class="col-sm-3 sidenav">
      
    </div>
    <div class="col-sm-6 text-left">
        <!--<div> -->
		<h2>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</h2>
		<div id="fillout">
		<h2>Please fill out form.</h2>
		<hr/>
		<form action="" method="post">
		<label>First Name:</label>
		<input type="text" name="fname" id="fname" required="required" placeholder="First Name"/><br /><br />
		<label>Last Name:</label>
		<input type="text" name="lname" id="email" required="required"  placeholder="Last Name"/><br/><br />
		<label>Address:</label>
		<input type="text" name="address" id="address" required="required"  placeholder="Address"/><br/><br />
		<label>City:</label>
		<input type="text" name="city" id="address" required="required"  placeholder="City"/><br/><br />
		<label>State:</label>
		<input type="text" name="state" id="state" required="required"  placeholder="State"/><br/><br />
		<label>Zip Code:</label>
		<input type="text" name="zip" id="zip" required="required"  placeholder="Zip Code"/><br/><br />
		<label>Phone:</label>
		<input type="text" name="phone" id="phone" required="required"  placeholder="603-111-2222"/><br/><br />
		<label>Large:</label>
		<input type="text" name="large" id="large" placeholder="21mm & up"/><br/><br />
		<label>Cut:</label>
		<input type="text" name="lsize" id="lsize" placeholder="Hexagon"/><br/><br />
		<label>Material:</label>
		<input type="text" name="lmatl" id="lmatl" placeholder="Aquamarine"/><br/><br />
		<label>Medium:</label>
		<input type="text" name="medium" id="medium" placeholder="11mm - 20mm"/><br/><br />
		<label>Cut:</label>
		<input type="text" name="msize" id="msize" placeholder="Round"/><br/><br />
		<label>Material:</label>
		<input type="text" name="mmatl" id="mmatl" placeholder="Smokey Quartz"/><br/><br />
		<label>Small:</label>
		<input type="text" name="small" id="small" placeholder="1mm - 10mm"/><br/><br />
		<label>Cut:</label>
		<input type="text" name="ssize" id="ssize" placeholder="Trillion"/><br/><br />
		<label>Material:</label>
		<input type="text" name="smatl" id="smatl" placeholder="Peridot"/><br/><br />
		<label>Cab or Carving 1:</label>
		<input type="text" name="desc1" id="desc1" placeholder="Description 1"/><br/><br />
		<label>Cab or Carving 2:</label>
		<input type="text" name="desc2" id="desc2" placeholder="Description 2"/><br/><br />
		<label>Cab or Carving 3:</label>
		<input type="text" name="desc3" id="desc3" placeholder="Description 3"/><br/><br />

		<input type="submit" value=" Save Form " name="submit"/><br />
</form>
</div>
		<!--</form>-->   
   <!-- </div> -->
    <div class="col-sm-3 sidenav">
      
    </div>
  </div>
</div>
		
<script src="bootstrap/js/bootstrap.min.js"></script>

<?php
error_reporting(E_ALL);
        ini_set('display_errors', '1');
		
if(isset($_POST["submit"])){
$hostname='XXXX';
$username='XXXX16';
$password='XXXX16';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=dblogin",$username,$password);

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
 
$sql = "INSERT INTO register (fname, lname, address, city, state, zip, phone, large, lsize, lmatl, medium, msize, mmatl, small, ssize, smatl, desc1, desc2, desc3)
VALUES ('".$_POST["fname"]."','".$_POST["lname"]."','".$_POST["address"]."','".$_POST["city"]."','".$_POST["state"]."','".$_POST["zip"]."','".$_POST["phone"]."','".$_POST["large"]."','".$_POST["lsize"]."','".$_POST["lmatl"]."','".$_POST["medium"]."','".$_POST["msize"]."','".$_POST["mmatl"]."','".$_POST["small"]."','".$_POST["ssize"]."','".$_POST["smatl"]."','".$_POST["desc1"]."','".$_POST["desc2"]."','".$_POST["desc3"]."')";


if ($dbh->query($sql)) {
     echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} 
else{
     echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}

    $dbh = null;
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }

}
?>

</body>
</html>

you may not be getting any error messages, but what exact output are you getting after you submit the form?

 

note: you will never see the Data not successfully Inserted alert, because an exception will be thrown if the query fails due to an error and code execution will go to the catch block.

if you do a 'view source' of the page in your browser, are the </body></html> tags present at the end of the output? What is the last output that is present in the 'view source'?

 

what i am suspecting is your web hosting doesn't allow the error_reporting/ini_set statements and you are getting a fatal php run-time error due to not having the PDO extension present and the code stops executing before it gets to the end of the page.

This is what is shown in the html file after the process completes.

 

<script src="bootstrap/js/bootstrap.min.js"></script>       SQLSTATE[HY000] [1045] Access denied for user 'xxxxxx'@'localhost' (using password: YES)   </body>   </html>

not sure why that error isn't being displayed.

 

are you sure about the hostname, username, and password? on most shared web hosting, the hostname is not going to be 'localhost' and the username can be some combination of your web account name and the database username you have chosen.

Edited by mac_gyver
  • Solution

Hi, I found out the problem, the error was generating and shown at the bottom of the page. I have sense figured out that the password was incorrect. I changed that and now it works. I want to correct the script so it's not supplying directly to the database as mentioned in the reply from "benanamen" but not sure how to do that. Do I have to remove the script from the form page and have the form call the script to insert the data to the database?

I have done this before but not recently. Any help would be appreciated. Thanks to all who replied.

Edited by vet911

you change how the sql statement is formed and how the data values are supplied to it - http://php.net/manual/en/pdo.prepare.php

 

unfortunately, emulated prepared queries are the default, despite the wishful thinking that pdo will automatically use real prepared queries if the database server supports them. when you make the pdo database connection, you need to turn emulated prepared queries off. add the following line to the section of code that's making the database connection - 

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); // run real prepared queries
Edited by mac_gyver
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.