Nihal Sahu
Nihal Sahu

Reputation: 189

php code working incorrectly and not querying database

I'm using php and a database to add books to a database.

HTML

<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>

PHP

$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');


$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";

mysqli_query($dbcon,$dbquery) or die('not queryed');

echo "Your book has been added to your online library";

I'm getting the reply ' not queryed'

Upvotes: 0

Views: 74

Answers (3)

Bharath Krishna
Bharath Krishna

Reputation: 37

Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.

I dont find any problem in the query, and also try putting

or die(mysqli_error());

and tell what exactly you can see.

If the type is varchar , you have to use single quotes around the values.

$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";

Upvotes: 0

randak
randak

Reputation: 2001

You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:

$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];

$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)

$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);

You can then add logic to check if the statement executed successfully.

Also, I think you just gave us your root password?

For more information about PDO, see this tutorial.

Upvotes: 1

uofc
uofc

Reputation: 550

try putting single quotes around the values

ie

$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";

Upvotes: 1

Related Questions