Beginer : PDO Insert does not work

Hai folks,

strange, my basic insert query does not work. i have no clue whats going on.

$query = $db->prepare("INSERT INTO 'visa_details'(company_id,visa_number)VALUES(:company_id,:visa_number)");
                      
$query->execute(array(':company_id' => $company_id, 
                      ':visa_number' => $visa_number));
$affected_rows = $query->rowCount();

echo "affected rows " . $affected_rows;

affected rows 0 :frowning:

You can check $db->errorInfo();

My guess is gonna be that youโ€™ve put quotes around your table name. Backticks (or nothing) go around table names. quotes go around string values.

1 Like

Similar to what @StarLion has suggested, you can also configure pdo to throw exceptions. This avoids the need to explicitly check for errors.

error_reporting(E_ALL);

$dsn = 'mysql:dbname=appgames;host=127.0.0.1';
$db  = new PDO($dsn, 'user', 'password');

// Throw exceptions on errors
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

// Use assoc arrays by default
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
1 Like

@afridy

remove the single quote as suggested by @StarLion, you can use backticks

`mytable`
1 Like

Those are only really necessary if you use reserved words as your table name or field names. Provided you avoid reserved words for your naming you can do away with the need for backticks completely.

Third party utilities only use backticks because they canโ€™t guarantee that the person using it has not been stupid and given either a table or field a name that is reserved.

1 Like

Excellent folks!
as your guys mentioned, removing the single quotes around table name did the job!

Thanks for all addition tips related to error handling etc etc.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.