0

I'm trying to use mysqli to insert data from a form into a database. However I'm not getting it to work :/

This is my code from the page you get to after you filled in the form. The form is not the problem because the variables $headin $author and $thecontent all have data in them. And in the real code database username password and name have real values :)

<html>
<head>

<title>Send!</title>
</head>

<body>

<?php

 ini_set('display_errors', 1); error_reporting(E_ALL); 
$DB_HOST = 'localhost';
$DB_USER = '**';
$DB_PASS = '***';
$DB_NAME = '***';
@ $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
echo 'Error.';
exit();
}

$author = $_POST['author']; 
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];

$query = 'INSERT INTO articles ('heading', 'author', 'content')
 VALUES ('$heading','$author','$thecontent')';   

$result = $db->query($query);
    if ($result) {
    echo $db->affected_rows."This was added.";
    } 
    else {
    echo "somethings gone very wrong.";
    }

$db->close();


?> 

</body>
</html>
2
  • Since you're using mysqli (good!) why aren't you using prepared statements? Your code is subject to SQL injection (say hello to Bobby Tables). Commented Oct 4, 2012 at 9:05
  • thanks I got it to work using prepared statements! Commented Oct 5, 2012 at 16:45

1 Answer 1

1

You cannot add single quotes ' on row names and you have to add double quotes for INSERT:

$query = "INSERT INTO articles (`heading`, `author`, `content`)
 VALUES ('$heading','$author','$thecontent')"; 

Also escape your strings:

$author = $db->real_escape_string($_POST['author']); 
$heading = $db->real_escape_string($_POST['heading']);
$thecontent = $db->real_escape_string($_POST['thecontent']);
Sign up to request clarification or add additional context in comments.

Comments

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.