query failedERROR: prepared statement "my_query" does not exist - php

Hello All
I'm trying to insert a form data into my postgreSQL DB in heroku through PHP and i tried all the solutions here but nothing solved my problem!. I can connect to the database but no operation worked well to me!. This error lead me to craziness!.
my code is:
<?php
$db_conn = pg_connect(" host="" port=5432 dbname="" user="" password="" ");
if(!$db_conn){
echo "Error : Unable to connect the database\n";
}
if (isset($_POST['savedata'])) {
$fn = $_POST ['fullname'];
$em = $_POST ['email'];
$ag = $_POST ['age'];
$ge = $_POST ['gender'] ;
$ci = $_POST ['city'] ;
$de = $_POST ['degree'];
$ex = $_POST ['experience'];
$jo = $_POST ['job'];
if($fn != "" and $em != "" and $ag != "" and $ge != "" and $ci != "" and $de != "" and $ex != "" and $jo != "") {
$data1="something to test";
$result = pg_prepare($db_conn, "my_query", "INSERT INTO members (fullname, email, age, gender, city, degree, experience, job) VALUES ($fn, $em, $ag, $ge, $ci, $de, $ex, $jo)");
$result = pg_execute($db_conn, "my_query", array($data1));
if (!$result){
error_reporting(E_ALL);
die("query failed".pg_last_error());
}
else {
echo "<script>";
echo "document.querySelector('.myalert').style.display = 'block';";
echo "setTimeout(function(){
document.querySelector('.myalert').style.display = 'none';
window.location.replace('home');
},5000);";
echo "</script>";
}
}
else {
echo "<script>";
echo "document.querySelector('.myalert1').style.display = 'block';";
echo "setTimeout(function(){
document.querySelector('.myalert1').style.display = 'none';
},2000);";
echo "</script>";
}
}
?>

You have syntax error in your code at the very first line.
Parse error: syntax error, unexpected '" port=5432 dbname="' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ')
There are also some other issues and oddities so it was just easier to rewrite some parts of your code.
I would also advice you to pay little more attention about the coding style, indentations and etc. It would be significantly easier to read and help you if the code were styled properly. PSR-2 Style Guide would be good place to start.
So here's the rewritten code, but note that I don't have PostgreSQL installed and that's why the code below isn't tested in any way. It should work, but there's also possibility that it doesn't.
See the comments in the code for further explanation.
// Change these credentials according to your needs, but without any quotes
$db_conn = pg_connect("host=localhost port=5432 dbname=mydb user=user password=pwd");
if (!$db_conn) {
die("Error : Unable to connect the database\n");
}
if (isset($_POST['savedata'])) {
$member_details = array(
$_POST['fullname'],
$_POST['email'],
$_POST['age'],
$_POST['gender'],
$_POST['city'],
$_POST['degree'],
$_POST['experience'],
$_POST['job']
);
}
// Iterates through the array and checks if there's any items of which has no proper value
foreach ($member_details as $key => $val) {
if (empty($val)) {
die($key . ' is empty.');
}
}
// Query inside single quotes, also variable names must be $1, $2, $3 etc
$query = 'INSERT INTO members (fullname, email, age, gender, city, degree, experience, job) VALUES ($1, $2, $3, $4, $5, $5, $7, $8)';
$result = pg_prepare($db_conn, "my_query", $query);
$result = pg_execute($db_conn, "my_query", $member_details);
if (!$result) {
// error actions
} else {
// success actions
}

Related

Error adding data in mysql table using PHP

I'm making a simple CURD operation using PHP and MYSQL. However I'm not able to insert/add data in the created table.
I think it might be a syntax error itself, but I can't figure out which one. The rest of the code works fine.
operation.php:
require_once("../CRUD/php/db.php");
$conn = createDB();
if(isset($_POST['create']))
{
createData();
}
function createData()
{
$name = textboxValue("name_type");
$age = textboxValue("age_type");
$gender = textboxValue("gender_type");
$email = textboxValue("email_type");
$contact = textboxValue("contact_type");
$dept = textboxValue("dept_type");
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES('$name', '$age', '$gender', $email', '$contact', '$dept');";
if(mysqli_query($GLOBALS['conn'],$sql))
{
echo "Data added";
}
else
{
echo "Error adding data";
}
}
function textboxValue($value)
{
$textbox = mysqli_real_escape_string($GLOBALS['conn'], trim($_POST[$value]));
if(empty($textbox))
{
return false;
}
else
{
return $textbox;
}
}
"Error adding data" gets echoed. I can share the html code as well if needed.
$sql = "INSERT INTO details(name,age,gender,email,contact,department)
VALUES(\"$name\", \"$age\", \"$gender\", \"$email\", \"$contact\", \"$dept\");";
and so? By the way one quote you forgot near $email

Data Not inserting into table PHP

The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.

Can't write to the database using INSERT INTO

I have written a form with server side validation using php and now my aim is to insert all the input's from my form into my database (which already has its tables). Below is my syntax:
//Example of one of my validations (for postcode input)
if (empty($_POST["postcode"])) {
$postcodeErr = "";
} else {
$postcode = test_input($_POST["postcode"]);
if(!preg_match("/^[0-9]*$/", $postcode)) {
$postcodeErr = "Only numeric characters";
}
else if (strlen($postcode) != 4) {
$postcodeErr = "Must be 4 digits in length";
}
}
}
//Connect to database server
$conn = mysql_connect("localhost", "-----", "------");
mysql_select_db("-------", $conn)
or die ('Database not found ' . mysql_error() );
// The SQL statement is built
$sql = "INSERT INTO Customer (name, address, suburb, state, postcode)
VALUES ('$_POST[name]', '$_POST[address]', '$_POST[suburb]', '$_POST[$state]', '$_POST[postcode]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn)
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //end of my php tag
When I run my form, I get a parse error saying that I have an unexpected T_FUNCTION. I know there is a lot above (tried to make it as simple as I can) but I can't seem to word around fixing the error and if I do, I just get another error. Am I writing the code correctly? Normally it's best when other people look at your work. Help will be much appreciated!
The quotes for $_POST['name'] and all other variables was missing in the post variable.
Try with
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$sql = "INSERT INTO Customer (name, Address, suburb, state, postcode)
VALUES ('$name', '$address', '$suburb', '$state', '$postcode')";
you also have one extra brace above database connection, use mysqli prepared statements for better security.
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "failed to connect to the database"; die();
}
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$stmt = $db->prepare("insert into `Customer` (name, Address, suburb, state, postcode) VALUES (?,?,?,?,?)";
$stmt->bind_param('sssss', $name, $address, $suburb, $state, $postcode);
$stmt->execute();
echo $stmt->affected_rows."record added";
mysql_close($conn) Needs to have a ; after it...
That's why the function after it is unexpected
Agreed with Fred, there seems to be an extra ending brace just above //Connect to database server which is breaking the code.
If that doesn't fix it, please copy/paste your full error message.
EDIT:
else if (strlen($postcode) != 4) {
needs to be
} else if (strlen($postcode) != 4) {
And there are two extra braces at the end of that if statement (just above the //Connect to database server)

Cannot execute sql INSERT query (mysql_query) in php script. PHP/MySQL -- Time Sensitive

UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.

PHP code not entering the data into database

$name = $_GET['fullname'];
$phone = $_GET['phone'];
$address = $_GET['address'];
$size = $_GET['size'];
$toppings = $_GET['toppings'];
$delivery = $_GET['type'];
mysql_connect ("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db ("pizzaorders");
$query ="INSERT INTO orders (fullname, phone, address, size, toppings, delivery) VALUES ('".$name."', '".$phone."', '".$address."','".$size."','".$toppings."','".$delivery.")";
$done=mysql_query($query);
echo $done;
$total = 0;
$total = sizecost() + deliverycost() + toppingcost();
echo " $name your {$_GET["size"]} pizza will come in 45 minutes.";
echo "Total: $ $total";
echo " Your Toppings are ";
foreach($toppings as $topping) {
echo $topping ;
}
echo "Your Delivery Type:{$_GET["type"]}";
echo "Database Updated";
function sizecost() {
$size = 0;
if ($_GET['size'] == "Small"){
$size+=5;
}
else if ($_GET['size'] == "Medium"){
$size+=10;
}
else if ($_GET['size'] == "Large"){
$size+=15;
}
return $size;
}
function toppingcost() {
$toppings = $_GET['toppings'];
foreach($toppings as $topping) {
$topping=1;
$topping=$topping+1;
}
return $topping;
}
function deliverycost() {
$deliverycost = 0;
if ($_GET['type'] == "delivery") {
$deliverycost += 5;
}
return $deliverycost;
}
Last value is missing a single quote at the end.
Use echo mysql_error after mysql_query
IMPORTANT
You MUST use mysql_real_escape_string() to protect against [my]sql injection.
You can save a lot of effort with using PDO;
$db = new PDO('mysql:host=localhost;dbname=pizzaorders', "root", "");
$query = $db->prepare("INSERT INTO orders
(fullname, phone, address, size, toppings, delivery)
VALUES (?,?,?,?,?,?)");
$query->execute(array($name, $phone, $address, $size, $toppings, $delivery));
Or you can just use the $_GET[] variables there.
first you could print the erros on the screen so you know what's wrong
$done=mysql_query($query) or die(mysql_error());
and second, you are missing a quote at the end
,'".$delivery.")"; should be ,'".$delivery."')";
Edit:
to answer your second question:
I don't think you can use $_GET['type'] inside a function
better to get the type outside a function and then pass it as a parameter, like follow:
$type = mysql_real_escape_string($_GET['type']);
deliverycost($type);
and in your function
function deliverycost($type)
{
if(empty($type))
{
//throw error, type cannot be empty
}
$deliverycost = 0;
if ($type == "delivery") {
$deliverycost += 5;
}
return $deliverycost;
}
Make sure you escape the single quotes like:
mysql_real_escape_string($name)
The query would be:
$query ="INSERT INTO orders (fullname, phone, address, size, toppings, delivery)
VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($phone)."', '".mysql_real_escape_string($address)."','".mysql_real_escape_string($size)."','".mysql_real_escape_string($toppings)."','".mysql_real_escape_string($delivery)."')";
Also echo the query to see what query is being sent to the database.

Categories