Jump to content

Strange query behavior


ludo1960

Recommended Posts

Hi guys,

In my connection.php I have:

$db->query("DROP TABLE IF EXISTS mydata") ;

$db->query("CREATE TABLE mydata
(
ID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
guid INT,
title VARCHAR(100),
body LONGTEXT,
term VARCHAR(100)
)"); 

and my query code :

$myarray = array (
    guid =>  100,
    title => "title test",
    body => "just a test",
    term => "term test",
);

$myplaceholders[] = '(' . implode (", ", array_fill(0, count($myarray), '?')) . ')'; //also tried '(?,?,?,?)'

$mykeys = implode(', ', array_keys($myarray));

array_push($values, ...array_values($myarray)); //also tried $values = array_values($myarray) ;

$res = $db->prepare("INSERT INTO mydata ($mykeys) VALUES " . join(', ', $myplaceholders)) ;

if ($res->execute($values)) {
    echo 'data inserted';
} else {
    echo 'error in query';
}

After executing the code, the table is created but no data is inserted. The strange thing is when I leave the create table statement  out of the connection.php and run the code the data is inserted. Any ideas where I'm going wrong?

Link to comment
Share on other sites

This works:

if ($db->query ( "DESCRIBE mydata" )) {
    
} else {

    $db->query("CREATE TABLE drupaldata
    (
    ID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
    guid INT,
    title VARCHAR(100),
    body LONGTEXT,
    term VARCHAR(100)
    
)"); 

}

oops, no it doesn't, how to create table if it does not exist?

Link to comment
Share on other sites

Don't create tables like this in your code. They should all be set up before your code gets to run at all.

If you want/need to create them using code, that's one thing, but that's something that should be a process completely separate from everything else. Something you run yourself because you need to set up the database. After that your code shouldn't have to consider the possibility that the table doesn't exist/exist in the state it's expecting.

Link to comment
Share on other sites

Or if it's a one-time process to create the table, just use the host's phpmyadmin tool to create the table and ensure that it is done correctly right in front of you.  THEN write your script.  Perhaps use cut/paste to save the input you use in that process in a notepad window until you get it correct or while experimenting or even to save it as a txt file once you are done if you think you'll need to re-create it.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.