Hi and thanks for reading.
I'm new to php (but I've been programming for a long time now) so I decided to use the pdo interface as a starter for my database queries. I did put a small script to test but it returns the database name as one of the columns name. Why?
Also for you pdo pros, once I instanciated a new pdo object without specifying the database name, how can I select it to prevent writing "databaseName.tableName" in my queries... See my script below:
try
{
$dbh = new PDO('mysql:host=localhost', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (Exception $e)
{
echo 'Erreur : ' . $e->getMessage() . '
$sth = $dbh->prepare("CREATE DATABASE IF NOT EXISTS myTest DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); $sth->execute();
$sth = $dbh->prepare("CREATE TABLE IF NOT EXISTS myTest.user( personID int NOT NULL AUTO_INCREMENT, PRIMARY KEY(personID), FirstName varchar(15), LastName varchar(15), Age int(3) 开发者_运维百科 )"); $sth->execute();
$sth = $dbh->prepare("INSERT INTO myTest.user (FirstName, LastName, Age) VALUES(?, ?, ?)"); $sth->execute(array("Charles", "Gagnon", "28"));
$sth = $dbh->query("SELECT * FROM myTest.user"); $result = $sth->fetch(PDO::FETCH_ASSOC);
$json = json_encode($result); print_r($json);
?>
So yeah, the print_r outputs this json:
{"personID":"1","FirstName":"Charles","user":"28"}
Pretty weird, it outputs the name of the table (user) instead of "Age" and the LastName field isn't there at all...
Any help will be appreciated, thanks!
Cannot replicate this. Using your exact code, I get
{"personID":"1","FirstName":"Charles","LastName":"Gagnon","Age":"28"}
Are you sure the myTest
database and table user
do not already exist with a different schema to what you're expecting (yet somehow still working for the INSERT
statement)?
Edit: There's no way your insert statement would work if the schema was different.
Also for you pdo pros, once I instanciated a new pdo object without specifying the database name, how can I select it to prevent writing "databaseName.tableName"
Just re-instate the PDO object, specifying the dbname
parameter in the DSN. Otherwise, I suppose you could try executing a use <database>;
command.
精彩评论