Jump to content

PHP inserting into MySQL


snookian

Recommended Posts

Hi guys I am using the code found here http://www.elated.com/articles/cms-in-an-afternoon-php-mysql/ with some alterations to try and insert data in a database via a php form, i have completed the example shown on that site and it works perfect, but I am now trying to adjust the code so that i have a user and admin section, but the form will not submit to the database.

 

Here is the for my form, page know as editArticles:

<?php include "templates/include/header.php" ?>

      <div id="userHeader">
        <h2><spanH1>Advertise!</spanH1> Place an advert for your book</h2>
        <p>You are logged in as <b><?php echo htmlspecialchars( $_SESSION['username']) ?></b>. <a href="user.php?action=logout"?>Log out</a></p>
      </div>

      <h1><?php echo $results['pageTitle']?></h1>

      <form action="user.php?action=newArticle" method="post">
        <input type="hidden" name="articleId" value="<?php echo $results['article']->id ?>"/>

<?php 
if ( isset( $results['errorMessage'] ) ) { ?>
        <div class="errorMessage"><?php echo $results['errorMessage'] ?></div>
<?php } ?>

        <ul>

          <li>
            <label for="booktitle">Book Title</label>
            <input type="text" name="booktitle" id="booktitle" placeholder="Title of the book" required autofocus maxlength="100" 
            	value="<?php echo htmlspecialchars( $results['article']->booktitle )?>" />
          </li>
          <li>
            <label for="author">Book Author</label>
            <input type="text" name="author" id="author" placeholder="Author of the book" required autofocus maxlength="50"  
            	value="<?php echo htmlspecialchars( $results['article']->author )?>" />
          </li>
          <li>
            <label for="edition">Edition</label>
            <input type="text" name="edition" id="edition" placeholder="Edition" required autofocus maxlength="2"
            	value="<?php echo ( $results['article']->edition )?>" />
          </li>
          <li>
		<label for="category">Category</label>
            <input type="text" name="category" id="category" placeholder="Book Category E.G Buisness" required autofocus maxlength="30"
            	value="<?php echo htmlspecialchars( $results['article']->category )?>" />
          </li>
          <li>
		<label for="module">Module</label>
            <input type="text" name="module" id="module" placeholder="Module" required autofocus maxlength="30"
            	value="<?php echo ( $results['article']->module )?>" />
          </li>
	  <li>
		<label for="price">Price</label>
            <input type="text" name="price" id="price" placeholder="Price" required autofocus maxlength="30"
            	value="<?php echo ( $results['article']->price )?>" />
          </li>
          <li>
		<label for="condition">Condition</label>
            <input type="text" name="condition" id="condition" placeholder="condition" required autofocus maxlength="30"
            	value="<?php echo ( $results['article']->condition )?>" />
          </li>
          <li>
		<label for="description">Description</label>
            <textarea name="description" id="description" placeholder="Description of the book including condition and associated modules" required maxlength="500" 
            	style="height: 15em;">
            	<?php echo htmlspecialchars( $results['article']->description )?></textarea>
          </li>
          <li>
          	<label for="Image">Image</label>
		<input type="file" name="Image" id="Image" /> 
	  </li>
          <li>
          <label for="pdate">Sale Date</label>
            <input type="date" name="pdate" id="pdate" placeholder="YYYY-MM-DD" required maxlength="10" 
            	value="<?php echo $results['article']->pdate ? date( "Y-m-d", $results['article']->pdate ) : "" ?>" />
          </li>


        </ul>

        <div class="buttons">
          <input type="submit" name="saveChanges" value="Save Changes" />
          <input type="submit" formnovalidate name="cancel" value="Cancel" />
        </div>
      </form> 
<?php if ( $results['article']->id ) { ?>
      <p><a href="admin.php?action=deleteArticle&articleId=<?php echo $results['article']->id ?>" onclick="return confirm('Delete This Article?')">Delete This Article</a></p>
<?php } ?>
<?php include "templates/include/footer.php" ?>

This is the form for the php, as you can see the form action is "new article"

This is the code for the action new article

function newArticle() {

  $results = array();
  $results['pageTitle'] = "New Article";
  $results['formAction'] = "newArticle";

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

    // User has posted the article edit form: save the new article
    $article = new Article;
    $article->storeFormValues( $_POST );
    $article->insert();
    header( "Location: admin.php?status=changesSaved" );

  } elseif ( isset( $_POST['cancel'] ) ) {

    // User has cancelled their edits: return to the article list
    header( "Location: admin.php" );
  } else {

    // User has not posted the article edit form yet: display the form
    $results['article'] = new Article;
    require( TEMPLATE_PATH . "/admin/editArticle.php" );
  }

}

As you can see the template is set to the above form page editArticle

Below is the code for the class "article" which contains the insert function and other functions such as construct, the storeFormValues which can is used in the "newArticle" function, and of course the insert function

class Article
{

  public $id = null;
  public $booktitle = null;
  public $author = null;
  public $edition = null;
  public $category = null;
  public $module = null;
  public $price = null;
  public $condition = null;
  public $description = null;
  public $image = null;
  public $pdate = null;

  public function __construct( $data=array() ) {
    if ( isset( $data['id'] ) ) $this->id = (int) $data['id'];
    if ( isset( $data['booktitle'] ) ) $this->booktitle = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['booktitle'] );
    if ( isset( $data['author'] ) ) $this->author = preg_replace ( "/[^\.\,\-\_\'\"\@\?\!\:\$ a-zA-Z0-9()]/", "", $data['author'] );
    if ( isset( $data['edition'] ) ) $this->edition = $data['edition'];
if ( isset( $data['category'] ) ) $this->category = $data['category'];
if ( isset( $data['module'] ) ) $this->module = $data['module'];
if ( isset( $data['price'] ) ) $this->price =(int) $data['price'];
if ( isset( $data['condition'] ) ) $this->condition = $data['condition'];
if ( isset( $data['description'] ) ) $this->description = $data['description'];
if ( isset( $data['image'] ) ) $this->image = $data['image'];
if ( isset( $data['pdate'] ) ) $this->pdate = (int) $data['pdate'];
  }

  public function storeFormValues ( $params ) {

    // Store all the parameters
    $this->__construct( $params );

    // Parse and store the publication date
    if ( isset($params['pdate']) ) {
      $sdate = explode ( '-', $params['pdate'] );

      if ( count($pdate) == 3 ) {
        list ( $y, $m, $d ) = $pdate;
        $this->pdate = mktime ( 0, 0, 0, $m, $d, $y );
      }
    }
  }

  public function insert() {

    // Does the Article object already have an ID?
    if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );

    // Insert the Article
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "INSERT INTO books ( booktitle, author, edition, category, module, price, condition, description, image, pdate ) 
		VALUES ( :booktitle, :author, :edition, :category, :module, :price, :condition, :description, :image, FROM_UNIXTIME(:pdate) )";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":booktitle", $this->booktitle, PDO::PARAM_STR );
    $st->bindValue( ":author", $this->author, PDO::PARAM_STR );
    $st->bindValue( ":edition", $this->edition, PDO::PARAM_STR );
$st->bindValue( ":category", $this->category, PDO::PARAM_STR );
$st->bindValue( ":module", $this->module, PDO::PARAM_STR );
$st->bindValue( ":price", $this->price, PDO::PARAM_INT );
$st->bindValue( ":condition", $this->condition, PDO::PARAM_STR );
$st->bindValue( ":description", $this->description, PDO::PARAM_STR );
$st->bindValue( ":image", $this->image, PDO::PARAM_STR );
$st->bindValue( ":pdate", $this->pdate, PDO::PARAM_INT );
    $st->execute();
    $this->id = $conn->lastInsertId();
    $conn = null;
  }

 

I would truly appreciate if someone is able to figure out what is going wrong, btw i dont get any errors when i click the save it takes mw to the next page and show a message i have set saying the changes have been saved but it doesnt actually save to me database.

 

If you have any questions or i need to explain more please let me know

 

Thanks in advance

 

 

Link to comment
Share on other sites

Thankyou for the reply, however I am quite new at php and having trouble placing that line.

 

I have tried it like this:

 

  public function insert() {

    // Does the Article object already have an ID?
    if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );

    // Insert the Article
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "INSERT INTO books ( booktitle, author, edition, category, module, price, condition, description, image, pdate ) 
		VALUES ( :booktitle, :author, :edition, :category, :module, :price, :condition, :description, :image, FROM_UNIXTIME(:pdate) )";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":booktitle", $this->booktitle, PDO::PARAM_STR );
    $st->bindValue( ":author", $this->author, PDO::PARAM_STR );
    $st->bindValue( ":edition", $this->edition, PDO::PARAM_STR );
$st->bindValue( ":category", $this->category, PDO::PARAM_STR );
$st->bindValue( ":module", $this->module, PDO::PARAM_STR );
$st->bindValue( ":price", $this->price, PDO::PARAM_INT );
$st->bindValue( ":condition", $this->condition, PDO::PARAM_STR );
$st->bindValue( ":description", $this->description, PDO::PARAM_STR );
$st->bindValue( ":image", $this->image, PDO::PARAM_STR );
$st->bindValue( ":pdate", $this->pdate, PDO::PARAM_INT );
    $st->execute();
    $this->id = $conn->lastInsertId();
    $conn = null;

if (!$st->execute()) {
    $arr = $sth->errorInfo();
    print_r($arr);
}

  }

 

And like this with a else statement

 

  public function insert() {

    // Does the Article object already have an ID?
    if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );

    // Insert the Article
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "INSERT INTO books ( booktitle, author, edition, category, module, price, condition, description, image, pdate ) 
		VALUES ( :booktitle, :author, :edition, :category, :module, :price, :condition, :description, :image, FROM_UNIXTIME(:pdate) )";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":booktitle", $this->booktitle, PDO::PARAM_STR );
    $st->bindValue( ":author", $this->author, PDO::PARAM_STR );
    $st->bindValue( ":edition", $this->edition, PDO::PARAM_STR );
$st->bindValue( ":category", $this->category, PDO::PARAM_STR );
$st->bindValue( ":module", $this->module, PDO::PARAM_STR );
$st->bindValue( ":price", $this->price, PDO::PARAM_INT );
$st->bindValue( ":condition", $this->condition, PDO::PARAM_STR );
$st->bindValue( ":description", $this->description, PDO::PARAM_STR );
$st->bindValue( ":image", $this->image, PDO::PARAM_STR );
$st->bindValue( ":pdate", $this->pdate, PDO::PARAM_INT );
    
    $this->id = $conn->lastInsertId();
    

if (!$st->execute()) {
    $arr = $sth->errorInfo();
    print_r($arr);
}
else
{
 $st->execute();
}
$conn = null;
  }

 

I'm sorry for not knowing much about the coding of php.

 

Appropriate any further help

Link to comment
Share on other sites

The code you're working with is too complex, you really should start with something simpler.  What you should do is replace the original $st->execute() like this:

 

 public function insert() {

    // Does the Article object already have an ID?
    if ( !is_null( $this->id ) ) trigger_error ( "Article::insert(): Attempt to insert an Article object that already has its ID property set (to $this->id).", E_USER_ERROR );

    // Insert the Article
    $conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
    $sql = "INSERT INTO books ( booktitle, author, edition, category, module, price, condition, description, image, pdate ) 
		VALUES ( :booktitle, :author, :edition, :category, :module, :price, :condition, :description, :image, FROM_UNIXTIME(:pdate) )";
    $st = $conn->prepare ( $sql );
    $st->bindValue( ":booktitle", $this->booktitle, PDO::PARAM_STR );
    $st->bindValue( ":author", $this->author, PDO::PARAM_STR );
    $st->bindValue( ":edition", $this->edition, PDO::PARAM_STR );
$st->bindValue( ":category", $this->category, PDO::PARAM_STR );
$st->bindValue( ":module", $this->module, PDO::PARAM_STR );
$st->bindValue( ":price", $this->price, PDO::PARAM_INT );
$st->bindValue( ":condition", $this->condition, PDO::PARAM_STR );
$st->bindValue( ":description", $this->description, PDO::PARAM_STR );
$st->bindValue( ":image", $this->image, PDO::PARAM_STR );
$st->bindValue( ":pdate", $this->pdate, PDO::PARAM_INT );

        # Replaced code is here:
        if (!$st->execute()) {
           $arr = $sth->errorInfo();
           print_r($arr);
        }
        # End of replaced code

    $this->id = $conn->lastInsertId();
    $conn = null;
  }

Link to comment
Share on other sites

It shows this error:

Fatal error: Call to a member function errorInfo() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/books/classes/Article.php on line 145

which is

$arr = $sth->errorInfo();

 

Whats confusing me is that i have used the example i originally gave the link to for an earlier project and it works perfect and all im trying to do is adapt it so there is more information stored in the mysql for books rather than articles and yet it doesn't work, its really starting to stress me out.

 

Thanks for your help

Link to comment
Share on other sites

Sorry,  I made a typo - it should be $st->errorInfo(), not $sth->errorInfo()

 

There's nothing mysterious about it starting to fail - the code is specialized for a particular type of data, and when you modify the data it can start to fail.  The solution is to add debugging so you can find exactly where it fails.  Once you narrow it down to a single location it is much easier to find why that single location is not working anymore.

 

Even generic (not specialized) code can start to fail when other code is modified, because it may start getting input it wasn't designed to get.

 

Have you modified the books table at all?  Or modfied any other tables?

Link to comment
Share on other sites

Thanks for all your help, I believe I have solved the problem, I stripped back all the code and started again gradually adding more fields, the issue seemed to revolve around around the condition and description fields, shortening these to cond and descr seemed to solve the issue, for now  :-\

 

Ian

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.