I cannot insert a data with Postgres and PHP - php

I'm developing a software with PHP and Postgres. So, I have a problem with insert code:
function create(){
$query = "INSERT INTO " . $this->table_name . " VALUES (" . $this->pess_nome . ")";
$result = pg_query($this->conn, $query);
if($result){
return true;
}else{
return false;
}
}
The error message :
Warning: pg_query(): Query failed: ERROR: column "test" does not exist LINE 1: INSERT INTO pessoa VALUES (test) ^ in C:\xampp\htdocs\Projeto_GPass\objects\pessoa.php on line 26

String values in SQL queries need to be enclosed in apostrophes or quotes. Modify the second line of your code to read:
$query = "INSERT INTO " . $this->table_name . " VALUES ('" . $this->pess_nome . "')";
EDIT: When you use a string value in a query and do not enclose it in quotes ("test") or apostrophes ('test'), PostgreSQL takes it as a name of the column, hence the error message.

Related

Doctrine Entity Manager gets Read Only error from database

public function save($itemId, $invoiceName)
{
$query = "
INSERT INTO invoice (item_id, invoice_name)
VALUES (" . $itemId . ",'" . $invoiceName . ")
";
$connection = $this->entityManager->getConnection('master');
return $connection->executeQuery($query);
}
Error while trying to insert into table:
An exception occurred while executing ' INSERT INTO invoice (item_id, invoice_name) VALUES (10600029,'FV/1823/06/2018/SOL') ': SQLSTATE[HY000]: General error: 1290 The MySQL server is running with the --read-only option so it cannot execute this statement
Checked connection to DB its fine.
Tried to save something with same user with a DBeaver DB client and it went through all fine - saved without any problem.
you need to close the connection used before to change connection and insert I think, try something like this:
$connection = $this->entityManager->getConnection()->close();
$query = "
INSERT INTO invoice (item_id, invoice_name)
VALUES (" . $itemId . ",'" . $invoiceName . ")
";
$connection = $this->entityManager->getConnection('master');
return $connection->executeQuery($query);
Even tho I specified 'master' the request was catched by slave all the time.
$entityManager->getConnection()->prepare('INSERT ... ')->execute();
Appeared to fix the problem.

I can't Insert row to database using php [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I am trying save to database row. But I get always error.
My code is:
function save_activation_key($connection, $username, $key) {
$date = time();
$is_used = 0;
$query = "INSERT INTO account_activation_key ( key, date, is_used)
VALUES ( '" . $username . "',"
. " '" . $date . "',"
. " '" . $is_used . "')";
$retval = mysql_query($query, $connection);
echo $retval;
$retval = mysql_query( $query, $connection );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
In $connection is valid connection to database.
Database structure:
id : int
key: varcha(45)
date: date
is_used: tinyint(1)
When I call my code I get error:
Could not enter data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key, date, is_used) VALUES ( 'uzivatelsky_jmeno', '1459971829', '0')' at line 1
Where is a problem?
Thanks for help
key is a MYSQL reserved word and should not really be used as column names.
MYSQL Reserved Words List can be found here https://dev.mysql.com/doc/refman/5.7/en/keywords.html
However if you wrap these column names in backticks you can get away with it.
You can also simplify your query string concatenation like the following, which makes it a lot easier to debug.
function save_activation_key($connection, $username, $key) {
$date = time();
$is_used = 0;
$query = "INSERT INTO `account_activation_key`
( `key`, `date`, `is_used`)
VALUES ( '$username', '$date', '$is_used')";
$retval = mysql_query($query, $connection);
echo $retval;
$retval = mysql_query( $query, $connection );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
}
BIG NOTE
Please dont use the mysql_ database extension, it
is deprecated (gone for ever in PHP7) Which means this code will never run when all that is available is PHP7 or greater.
Especially if you are just learning PHP, spend your energies learning the PDO or mysqli_ database extensions,
and here is some help to decide which to use
probably your query contains an error at the place where you are giving integer as a string , like your string
'" . $username . "',"
. " '" . $date . "',"
. " '" . $is_used . "'
should be :
'" . $username . "',"." . $date . ","." . $is_used . "
the integers should'nt be with single qoutes " ' "
probably this is the mistake!

Unknown Column in 'field list' php mysql

I've looked everywhere but I cant find an answer for this question. I've seen several solutions that have helped people, but when I try it, I see I'm doing everything right and have nothing to fix. I'm making a forum and i'm trying to insert these into a mysql table but every time I try it says:
Unknown column '6c09e4fe82d47011bf9b25b05946307f' in 'field list'.
The long code is a user id for one of the users, and Its supposed to get inserted, but for some reason its looking for a column with that name. I've only gotten up to the first query with an error so the second part might be totally fine, I don't know.
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
". $_SESSION['userid'] ."
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'You did everything right, yet there is an error. WEIRD RIGHT???<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
". $_SESSION['userid'] ."
)";
$result = mysql_query($sql);
You're not quoting the string in the INSERT:
". $_SESSION['userid'] ."
Should be:
'". $_SESSION['userid'] ."'
" . mysql_real_escape_string($_POST['topic_cat']) . ",
needs to be enclosed in quotes
'" . mysql_real_escape_string($_POST['topic_cat']) . ",'
Just echo $sql; and you will see your error.
Also make sure you session_start();

MySQL Syntax error on Insert Query from PHP

I'm getting a non-descriptive syntax error on a MYSQL query from PHP. If I "echo" the text of the query and paste it into a MySQL query window, the code works. Here is the SQL for the query, the error code, and the error message...
INSERT INTO ADVERTISEMENTS (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (2, 'Test New Ad', 'http://www.google.com', 'red_arrow.png', '#000000', '1980-05-11 00:00:00', '2020-05-01 00:00:00', 5, '2013-07-14 22:21:59');
Error Code: 1064
Error Msg: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Here is the PHP code I am using...
$link = mysqli_connect($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
$advertisementNameNew = mysqli_real_escape_string($link, $_POST['advertisementNameNew']);
$destinationURLNew = mysqli_real_escape_string($link, $_POST['destinationURLNew']);
$dropboxUploadFile = mysqli_real_escape_string($link, $_POST['dropboxUploadFile']);
$backgroundColorNew = mysqli_real_escape_string($link, $_POST['backgroundColorNew']);
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
echo "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');<br />";
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS(`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES ($tmpUserID, '$advertisementNameNew', '$destinationURLNew', '$dropboxUploadFile', '$backgroundColorNew', '$bannerStartDateNew', '$bannerEndDateNew', $bannerSetTimerNew, '$tmpAddDate');")) {
printf("Error Code: %s\n", mysqli_errno($link));
echo "<br />";
printf("Error Msg: %s\n", mysqli_error($link));
}
I know that the database connection is working. I am able to select and update tables. I can also insert into other tables with different queries.
I am open to any suggestions.
Thank you in advance for your help!
I see a few errors in your query strings.
First, all your variables are passed as literal strings: "... VALUES ($tmpUserID, '$advertisementNameNew', ..." should be "... VALUES (".$tmpUserID.", '".$advertisementNameNew."', ...".
Second, I see missing quotes around $bannerSetTimerNew.
Third, there is an extra ;.
here's how I would write the query:
if (!mysqli_query($link, "INSERT INTO ADVERTISEMENTS (user_id, ad_name, click_url, img_url, bg_color, start_date, end_date, timer_delay, add_date) VALUES (".$tmpUserID.", '".$advertisementNameNew."', '".$destinationURLNew."', '".$dropboxUploadFile."', '".$backgroundColorNew."', '".$bannerStartDateNew."', '".$bannerEndDateNew."', '".$bannerSetTimerNew."', '".$tmpAddDate."')")) { ...
I didnt test it though.
hope this helps.
I see a ; at the end of the query. Are you sure that should be there?
There are two things
1. Remove the ; from at the end of the query.
2. I hope timer_delay field has datatype "Int" if its a VARCHAR then you will have to include quotes for that field value.
I hope this will help.
Passerby, thank you for your comment. This was my first experience with using mysqli, I changed my query to use the "bind_param" method, and everything works now. For anyone else with a similar problem, here is the corrected code...
$mysqli = new mysqli($UM_Settings["database_options"]["server_name"], $UM_Settings["database_options"]["username"], $UM_Settings["database_options"]["password"], $UM_Settings["database_options"]["database_name"]);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$advertisementNameNew = $_POST['advertisementNameNew'];
$destinationURLNew = $_POST['destinationURLNew'];
$dropboxUploadFile = $_POST['dropboxUploadFile'];
$backgroundColorNew = $_POST['backgroundColorNew'];
$bannerStartDateNew = DateStringToMySQL($_POST['bannerStartDateNew']);
$bannerEndDateNew = DateStringToMySQL($_POST['bannerEndDateNew']);
$bannerSetTimerNew = intval($_POST['bannerSetTimerNew']);
$tmpUserID = UM_GetCookie("UM_UserID");
$tmpAddDate = DateStringToMySQL('now');
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO `ADVERTISEMENTS` (`user_id`, `ad_name`, `click_url`, `img_url`, `bg_color`, `start_date`, `end_date`, `timer_delay`, `add_date`) VALUES (?,?,?,?,?,?,?,?,?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("issssssis",$tmpUserID, $advertisementNameNew, $destinationURLNew, $dropboxUploadFile, $backgroundColorNew, $bannerStartDateNew, $bannerEndDateNew, $bannerSetTimerNew, $tmpAddDate)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$_GET['ad_id'] = $stmt->insert_id;
$stmt->close();

SQL syntax is ok but php still throw error

My sql query when I check manually in phpmyadmin works fine, but when I try to handle it through php mysql_query throw me a syntax error. How to solve this issue?
Error message:
Invalid query:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ))' at line 1
Whole query:
INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login)
VALUES ('1000001010101010', 'Bart Roza', 'Bart', 'Roza', 'lalalala#gmail.com','http://www.facebook.com/profile.php?id=1000001010101010','2011-05-07 11:15:24');
INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ));
My php function:
public function createUser()
{
$time = date("Y-m-d H:i:s");
$insert = "INSERT INTO users (id_fb, name, first_name, last_name, email, link, first_login) VALUES (" .
"'" . $this->me['id'] . "', " .
"'" . $this->me['name'] . "', " .
"'" . $this->me['first_name'] . "', " .
"'" . $this->me['last_name'] . "', " .
"'" . $this->me['email'] . "'," .
"'" . $this->me['link'] . "'," .
"'" . $time . "'); " .
"INSERT INTO scores( user_id ) VALUES (LAST_INSERT_ID( ));";
$result = mysql_query($insert);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $insert;
die($message);
}
}
EDIT:
Thanks for the solution!
Since mysql_query accepts only one query you need to split your query string into 2 separated queries and perform it with 2 mysql_query calls.
You can not run multiple queries in once using mysql_query function. you have to run these two queries with separate mysql_query call
mysql_query() sends a unique query
(multiple queries are not supported)
AS #zerkms and #Shakti said, mysql_query does not support multiple queries. If you want to use such functionality, consider migrating to mysqli. It supports multiple queries in a single packet by mysqli_multi_query

Categories