PHP code not entering the data into database - php

$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.

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

query failedERROR: prepared statement "my_query" does not exist

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
}

PHP form submiting

I have a form with four values, player1, player2, awayTeam, and homeTeam.
After checking if values are not empty it does not want to send results to database. I am not sure why it does not want to submit.
There are as well two random numbers which will be compared and based on if num1 > num2 record should be submitted.
<?php
$link = mysqli_connect("localhost","test", "passowrd", "test" );
if (mysqli_connect_error()) {
die ("DB has not been connected");
}
// create two random numbers
$Num1 = rand();
$Num2 = rand();
if (isset($_POST['submit'])) {
$playerOne = mysqli_real_escape_string ($link, $_POST['playerOne']);
$playerTwo = mysqli_real_escape_string ($link, $_POST['playerTwo']);
$awayTeam = mysqli_real_escape_string ($link, $_POST['awayTeam']);
$homeTeam = mysqli_real_escape_string ($link, $_POST['homeTeam']);
//check if player one is empty
if (empty($playerOne)) {
echo "Game Creator PSN required!" . "<br>";
}
//check if player two is empty
if (empty($playerTwo)) {
echo "Second Player PSN required!";
}
} else {
//compare two numbers
if ($Num1 > $Num2) {
$sql = "INSERT INTO randomizer (playerOne, playerTwo, awayteam, homeTeam) VALUES (' $playerOne', '$playerTwo', '$awayTeam', '$homeTeam')";
if ($link->query($sql) === true) {
echo "Record Added Sucessfully";
} else {
echo "There was a problem";
}
} else {
$sql = "INSERT INTO randomizer (playerOne, playerTwo, awayteam, homeTeam) VALUES (' $playerTwo', '$playerOne', '$awayTeam', '$homeTeam')";
if ($link->query($sql) === true) {
echo "Record Added Sucessfully";
} else {
echo "There was a problem";
}
}
}
?>
if post data is null, you did nothing. I've never see exit or other exit words, in the SQL words you'll get errs
what different with $num1 > $num2 in your code? they executed the same codes

for loop is not executed /getting error like loop is not working

In my example below the for loop is not executed and / or my data is not being inserted into the database. What can I change?
<?php
include('connection.php');
{
if(isset($_POST['Submit']))
{
date_default_timezone_set('Asia/Calcutta');
$date = date('Y-m-d H:i:s', time());
for ($i=1; $i<=$_POST["NUM_STUDENTS"]; $i++) {
$STD = "STUDENT_ID".$i;
$DS = "DISCOUNT".$i;
$LV = "LEAVE".$i;
$FN = "FINE".$i;
$sql = "INSERT INTO ATTENDANCE";
$sql .= "(SESSION_ID,ORG_ID,GRADE_ID,MONTH,STUDENT_ID,DISCOUNT,LEAVE,FINE,SOURCE,CREATEDTTM,UPDDTTM,DELETE_FLAG)";
$sql .= "VALUES ";
$sql .= "('".$_POST["SESSION_ID"]."','".$_POST["ORG_ID"]."','".$_POST["GRADE_ID"]."','".$_POST["MONTH"]."','".$_POST[$STD]."','".$_POST[$DS]."','".$_POST[$LV]."','".$_POST[$FN]."' ";
$sql .= ",'".$_SESSION['login_name']."','".$date."','".$date."','N')";
$objQuery_2 = mysql_query($sql);
if($objQuery_2)
{
echo"<script>alert('Attendance Fine Added Successfully')</script>";
header("refresh:0;url=attendance_srch.php");
exit();
}
else
{
echo"<script>alert('Please Check Data')</script>";
header("refresh:0;url=attendance_srch.php");
exit();
}
}
}
mysql_close($bd);
ob_flush();
}
?>
You have left a lot space here between ? and > must be ?> . [This is one of the errors]
<?=$objResult["OPERATOR_ID"];? >">
^^^
must be
<?=$objResult["OPERATOR_ID"];?>">
Array keys are case sensitive. If the actual names of the input is OPERATOR_ID, then you can't access it with $_GET['operator_id'], you have to use $_GET['OPERATOR_ID'].
Another problem is that you have an extra set of braces. So you're doing all the database code even if the if (isset($_GET['OPERATOR_ID']) is false.

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.

Categories