PostgreSQL insert not working - php

I'm trying to set up a simple database with Heroku/PGSQL. So far I've made a connection and created the table I want, but whenever I try and insert data to the table nothing happens.
For testing purposes, I'm using the code
$dbconn = pg_connect(pg_connection_string());
if (!$dbconn) {
echo "Database connection error. ";
}
else {
// Create table
$create="CREATE TABLE IF NOT EXISTS users (
id INT PRIMARY KEY NOT NULL,
gender CHAR(30),
age INT,
location CHAR(30),
timestamp CHAR(30)
)";
// Execute query
if (pg_query($dbconn,$create)) {
echo "Table users created successfully. ";
}
else {
echo "Error creating table. ";
}
}
function insert() {
$dbconn = pg_connect(pg_connection_string());
if (!$dbconn) {
echo "Database connection error 2. ";
}
else {
# Insert query
$insert = "INSERT INTO users (id, gender, age, location, timestamp) VALUE (1234, 'male', 99, 'UK', '31/05/2013')";
# Execute query
if (pg_query($dbconn,$insert)) {
echo "Data entered successfully. ";
}
else {
echo "Data entry unsuccessful. ";
}
}
}
When run, it returns "Table users created successfully." However, when I call the $$insert$$ function (I will later use this to insert different values into the table) it always returns unsuccessful.
What am I doing wrong?

$insert = "INSERT INTO users (id, gender, age, location, timestamp)
VALUES (1234, 'male', 99, 'UK', '31/05/2013')";
maybe you shouldn't use char for timestamp

In the insert statement, VALUE should be VALUES.
Anyway, you should try to recover the error message given by database. I think it's possible in PHP. You'll have much more information about the reason of your error.

Related

Error SQLSTATE[HY093]: Invalid parameter number: in php PDO statement

im a newbie in php and im facing this problem...i get with it 3 days and im going mad... ;). Im trying to implement a table with users of a web application. So i have to check that the user doesnt exist.
My sql table:
DROP TABLE users;
CREATE TABLE users (
idUser INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
mail VARCHAR(45) NOT NULL UNIQUE,
name VARCHAR(45) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
role enum ("admin", "user"),
state BOOLEAN,
forgotpass VARCHAR(32) NOT NULL
);
Also this code works ( test if the user already exists in the table):
//$query="SELECT mail FROM proba.users WHERE mail='{$correu}'";
$sql = 'SELECT * FROM users WHERE mail = :mailparam';
//$sql = 'SELECT * FROM users';
$stmt = $con->prepare($sql);
// 2. execute to insert a row
// with an associative array
$stmt->execute(
array(':mailparam'=>$correuFormulari)
);
// 3. get all rows
$rows = $stmt->fetchAll();
foreach ($rows as $rowActual) {
echo $rowActual['mail'] . "<br>";
echo $rowActual['password'] . "<br>";
}
But following the same logic i cant insert an element:
if(count($rows) > 0){
echo "L'usuari ja existeix";
echo "<p><a href='registreUsuari.php'>Torna</a></p>";
} else{
echo "Usuari no trobat. Passem a insertar";
//INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES ("p#gmail.com", "pepe","user", "pepito", current_Time,"forgotpass");
$user="admin";
$sqlinsert = 'INSERT INTO users (mail, password, role, name,forgotpass) VALUES (:mail, :passwordform,:usuari, :nomFormulari,:forgotpass)';
//$sql = 'SELECT * FROM users';
$stmtinsertar = $con->prepare($sqlinsert);
// $stmt = $con->prepare("INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES (:mail, :password,:user, :nomFormulari, :data,:forgotpass)");
/* $stmtinsertar->bindParam(':mail', $correuFormulari);
$stmtinsertar->bindParam(':password', $passwordFormulari);
$stmtinsertar->bindParam(':user', $user);
$stmtinsertar->bindParam(':nomFormulari', $nomFormulari);
//$stmt->bindParam(':data', $data);
$stmtinsertar->bindParam(':forgotpass', "forgotpass");
INSERT INTO users (mail, password, role, name,forgotpass) VALUES ("hola#g,aoƱ", "pepe","user", "pedro","forgot")
*/
try
{
//$stmtinsertar->execute();
$stmt->execute(
array(':mail'=> "$correuFormulari",
':passwordform'=> "$passwordFormulari",
':usuari'=> "$user",
':nomFormulari'=> "$nomFormulari",
':forgotpass'=> "forgotpass")
);
}
catch(PDOException $e)
{
handle_sql_errors($selectQuery, $e->getMessage());
}
echo "S'ha creat l'usuari";
//header('Location: '.'login.php');
// $stmt->close();
}
I enter in the correct if, but i cant insert into the table....
The error shows something like:
pepekjjp#gamil.comConexio : object(PDO)#2 (0) { } hoola0Usuari no trobat. Passem a insertar
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
As you can read in the code i also tried to use bind->Params....
Any help would be apreciated.
Also would like to know, which form of executing PDO is preferred, using bindParameter or using an array.
Thanks in advance

Inserting values to mysql database and retrieving them to insert to another table

I'm trying to insert values to mysql database table called pointofcontact and then retrieve the primary key called pocid to insert to another table called students.
Somehow my code always return the pocid to be 0 and i have no idea why. Gladly to get some help. Any help would be greatly appreciated! Here is my code:
$query="insert into pointofcontact(Username,Password,FirstName,LastName,ContactNumber,EmailAddress,Address,Gender,Status,BackupContactNumber,ProfilePic) values ('$username','$password','$firstname','$lastname','$mobilenumber','$email','$address','$gender','Normal','$backup','$attch')";
if($con->query($query) === TRUE)
{
$query2="select POCID from pointofcontact where username= '$username'";
$result2=$con->query($query2);
if($result2 ->num_rows > 0)
{
while($row2 = $result2->fetch_assoc())
{
$pocid = $row2['POCID'];
$query3= "insert into student(StudentFirstName, StudentLastName, Allergies, NRIC, POCID) values ('$cfirstname','$clastname','$callergies','$cnric','$POCID')";
}
if($con->query($query3) === TRUE)
{
}
else
{
}
}
}
else
{
echo "error";
}
I haven't tested this, but it should do what you need:
// assuming proper validation and escaping is completed...
if($con->query("INSERT INTO pointofcontact (Username,Password,FirstName,LastName,ContactNumber,EmailAddress,Address,Gender,Status,BackupContactNumber,ProfilePic) VALUES ('$username','$password','$firstname','$lastname','$mobilenumber','$email','$address','$gender','Normal','$backup','$attch');"){
$POCID=$con->insert_id;
if($con->query("INSERT INTO student (StudentFirstName, StudentLastName, Allergies, NRIC, POCID) VALUES ('$cfirstname','$clastname','$callergies','$cnric','$POCID');")){
// Pass
}else{
// Fail
}
}else{
// Fail
}
check your database table design for POCID column. When you created that table you must add it as primary key and auto_increment ...
CREATE TABLE table_name (id int primary key auto_increment,....)
If you already did this then, use mysqli_insert_id() to get the last inserted id.

INSERT & CREATE TABLE doesn't seem to be working

I'm currently experiencing some problems.
Basically, I use PDO and I want to create a table and insert some stuff into the table.
I've tried searching for solutions, but it doesn't seem like anything is working.
Please take a look at this:
public function install()
{
global $con;
$sql = "CREATE TABLE if not exists users
(id INT(11) PRIMARY_KEY,
uname VARCHAR(30) ,
pass VARCHAR (40))";
$sq = $con->query($sql);
if ($sq)
{
echo "Table successfully created!";
}
else
{
$this->errors[] = 'Error creating table: users';
}
$sql_code = "INSERT INTO users (
`uname`,
`pass` ) VALUES(
`$this->username`,
`$this->password`
)";
$sq1 = $con->query($sql_code);
if ($sql_code)
{
echo "Successfull!";
}
else
{
echo "Error creating admin user!";
}
}
NOTE: The database connection is set in another file called config.php and I've also included the config.php file to the code.
Well, there could be plenty of things going on, perhaps at the same time.
Maybe your database connection is failing (I'd recommend passing the connection $con by reference to the function install rather than using the global keyword).
Maybe you don't have enough rights to create a table in the database.
Also you are not binding your parameters, this would be the correct way to do it:
$sql_code = "
INSERT INTO users (
uname,
pass
)
VALUES (
:userName,
:password
);
";
$sq1 = $con->prepare($sql_code);
$sq1->bindParam(':userName', $userName);
$sq1->bindParam(':password', $password);
$sq1->query($sql_code);

INSERT INTO table1 values FROM table2 WHERE

I've looked around nothing seems to be working for me. I have a button when pushed it INSERTS data into 1 table-1, then it gets values from table-3 to put in table-2 where in they the ID is the same.
if ($movieTime != "") {
$query = "SELECT SchedID FROM tblCinemaSched WHERE TheaterID='$tid' AND CinemaID='$cid' AND MovieDate='$date' AND MovieTime='$movieTime'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$numRows=$conn->numRows($result);
if ($numRows<=0) {
$query = "INSERT INTO tblCinemaSched SET TheaterID='$tid', CinemaID='$cid', MovieDate='$date', MovieTime='$movieTime', MovieID='$movieId', PriceAmt='$priceId', CrtBy='$username', CrtDate=NOW()";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
//get seat defaults from tblCSeats
$query = "INSERT INTO tblSSeats SELECT TheaterID, CinemaID, '$date', '$movieTime', SeatID, RowNo, ColumnNo, Handicap, Status, LeftSeat, RightSeat, NULL, NULL,NULL,NULL,NULL,NULL,NULL,'$username',NOW() FROM tblCSeats WHERE TheaterID='$tid' AND CinemaID='$cid'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$errorStr = "Succesfully added schedule.";
}
else {
$errorStr = "There's already an existing schedule for the specified time.";
}
You see tableCSeats has more than 1 row that has the same ID meaning I want to insert multiple data from tableCSeats to tableSSeats. tableSSeats is a has no data in it yet.
At a blind guess, it would seem that you are looking for INSERT ... SELECT statement.
check the return values of your queries. You always get "Succesfully added schedule." because you don't check if the queries were succesful. Ex:
if(!$result=$conn->executeUpdate($query)) {
die('error');
}
or something like that.

Beginner PHP: I can't insert data into MYSQL database

I'm learning PHP right now and I'm trying to insert data into a MySQL database called "pumpl2" The table is set up like this.
create table product
( productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
I have a form and want to insert the fields from the form in the database. Here is what the php file looks like.
<?php
// create short variable names
$price = $_POST['price'];
$value = $_POST['value'];
$description = $_POST['description'];
if (!$price || !$value || !$description) {
echo "You have not entered all the required details.<br />"
."Please go back and try again.";
exit;
}
# $db = new mysqli('localhost', 'pumpl', '********', 'pumpl2');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "insert into pumpl2 values
('".$price."', '".$value."', '".$description."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." product inserted into database.";
} else {
echo "An error has occurred. The item was not added.";
}
$db->close();
?>
When I submit the form, I get an error message "An error has occurred. The item was not added."
Does anyone know what the problem is? Thank you!
This should give you more information:
echo "An error has occurred: " . $db->error();
You are trying to insert into the table called pumpl2, but the CREATE TABLE statement created a table called product.
In addition, as ZeissS noted, you have to consider the following:
CREATE TABLE product (
productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
Query OK, 0 rows affected (0.09 sec)
INSERT INTO product VALUES (1, 1, 'test');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
To solve that error, you need to explicitly specify the list of the columns:
INSERT INTO product (price, value, description) VALUES (1, 1, 'test');
Query OK, 1 row affected (0.03 sec)
You only insert three columns but have four defined in your table. Thus you have to name the columns explicitly:
INSERT INTO tableName (ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'C')
$query = "insert into pumpl2.product (price, value, description) values('" .
$db->read_escape_string($price) . "', '".
$db->read_escape_string($value) . "', '" .
$db->read_escape_string($description) . "')";
$result = $db->query($query);
And an obligatory XKCD cartoon:
Your query is wrong, you didn't have the columns specified.
Try it with:
"INSERT INTO pumpl2 (price, value, description) VALUES ('".$price."', '".$value."', '".$description."')"
Besides that, do not use the $_POST values to enter them directly into the database. Search for SQL Injection on this one. Use mysql_real_escape_string on the $_POST data first, or even better use prepared statements.
It could be several reasons.
Try
echo "Errormessage: ".$db->error;
to get more details, why the Insert didn't work.
Your table is called products not pumpl2. Furthermore you should do:
insert into product (price, value, description) values ( ...

Categories