get Server
get Server

Reputation: 3

PDO dont work when trying to execute INSERT command

i'm trying to INSERT a sql query but it does not work - I got no errors, $pdo->errorInfo(); only returns Array and in the mysql is nothing to see! Im 100% sure that $text, $file and $title is set (i've check that with echo) In every other php file this pdo connection works with include but not in the dev.php what should i do???

datenbank.php

<?php
$pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'password');
?>

dev.php

include("datenbank.php");
// Prepare an insert statement
$post = $pdo->prepare("INSERT INTO news (text, date, file, title) VALUES ($text, NOW(), $file, $title)");
$post->execute(); 
$help = $pdo->errorInfo();

Upvotes: 0

Views: 50

Answers (2)

crespo5
crespo5

Reputation: 81

You don't use the parameters markers in your prepare PDO stament. When you prepare a query using PDO extension, you need put markers in your query statement and indicate the value of those markers in the execute function like an associative array.

You can use markers like :marker or question marks ? and your query would be like that:

include("datenbank.php");
// Prepare an insert statement with marks params
$post = $pdo->prepare(INSERT INTO news (text, date, file, title) VALUES (:text, NOW(), :file, :title));
//execute statements with the marks values in prapare function params
$post->execute(array(':text' => $text, ':file' => $file, ':title' => $title)); 

Edit: PD: This prevents the SQL inyection.......

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133370

for string value you need quote

$post = $pdo->prepare("INSERT INTO news (text, date, file, title) 
   VALUES ('$text', NOW(),'$file', '$title')");

anyway you should not use php var in sql , you are at risk for sqlinjection .. use prepared statements and binding param instead

$stmt = $conn->prepare("INSERT INTO news (text, date, file, title) 
         VALUES (:text, NOW(), :file, :title)");
$stmt->bindParam(':text', $text);
$stmt->bindParam(':file', $file);
$stmt->bindParam(':title', $title);

 $stmt->execute();

Upvotes: 0

Related Questions