I tried checking if a table already exists and if it doesn't it should create it and insert the given data to the table but if it already exists it should just insert the data directly. But I am just getting a plain page. The pg_error(); is not outputting nothing. Could someone help please?.. Below is the code;
<?php
$pra = "SELECT * FROM people";
$decks = pg_query($connection, $pra);
if(!$decks){
$sql = "CREATE TABLE people(
mom INT PRIMARY KEY NOT NULL,
non TEXT NOT NULL,
ooo INT NOT NULL,
ppp INT NOT NULL,
aqqq TEXT,
pq TEXT
)";
$ins = " INSERT INTO people (mom, non, ooo, ppp, aqqq, pq)
VALUES(
'$mom', '$non', '$ooo’, '$ppp’, '$aqqq', '$pq')";
$rcon =pg_query($connection, $ins);
if(!$rcon){
pg_last_error($connection);
}else{
echo "Record added to database"; //success
confirmation
}
}
?>
Some how the table here is created because I can see it in the database via terminal. But apart from that everything is coming blank and no error messages.
Please try something like this. Note the use of pg_query_params()
instead of pg_query()
for the insert to guard against SQL injection.
<?php
$pra = "SELECT * FROM people";
$decks = pg_query($connection, $pra);
if(!$decks){
$sql = "CREATE TABLE people(
mom INT PRIMARY KEY NOT NULL,
non TEXT NOT NULL,
ooo INT NOT NULL,
ppp INT NOT NULL,
aqqq TEXT,
pq TEXT
)";
$rcon = pg_query($connection, $sql);
if(!$rcon){
echo pg_last_error($connection);
} else {
echo "Database table created"; //success confirmation
}
}
$val_array = array($mom, $non, $ooo, $ppp, $aqqq, $pq);
var_dump($val_array);
$ins = " INSERT INTO people (mom, non, ooo, ppp, aqqq, pq)
VALUES($1, $2, $3, $4, $5, $6)";
$rcon =pg_query_params($connection, $ins, $val_array);
if(!$rcon){
echo pg_last_error($connection);
} else {
echo "Record added to database"; //success confirmation
}
?>