PHP - Notice: Undefined variable happening twice - php

I'm getting the following two errors when loading my page:
Notice: Undefined variable: realtor in C:\Program Files\EasyPHP-5.3.9\www\cglst\images\addform.php on line 255
and
Notice: Undefined variable: phone in C:\Program Files\EasyPHP-5.3.9\www\cglst\images\addform.php on line 256
I do define both those variables, though, so I don't understand why I'm getting these errors. Here is my code:
function addListing() {//if data was provided, insert it into database and confirm
//this will allow everything to be sanitized properly
require_once "sanitize.php";
$submitted = false;
//Checking if values were passed
if (isset($_POST['area']) &&
isset($_POST['price']) &&
isset($_POST['address']) &&
isset($_POST['bedrooms']) &&
isset($_POST['fullbath']) &&
isset($_POST['halfbath']) &&
isset($_POST['sqft']))
//if passed, sanitize and set variables accordingly
{
$area = sanitizeOne(get_post('area'), 'plain');
$price = sanitizeOne(get_post('price'), 'int');
$address = sanitizeOne(get_post('address'), 'plain');
$bedrooms = sanitizeOne(get_post('bedrooms'), 'int');
$fullbath = sanitizeOne(get_post('fullbath'), 'int');
$halfbath = sanitizeOne(get_post('halfbath'), 'int');
$sqft = sanitizeOne(get_post('sqft'), 'int');
$submitted = true;
}
//optional fields
if (isset($_POST['remarks']))
{
$remarks = sanitizeOne(get_post('remarks'), 'plain');
}
else
{$remarks = ' ';}
if (isset($_POST['realtor']))
{
$remarks = sanitizeOne(get_post('realtor'), 'plain');
}
else
{$realtor = "Anne-Marie Pelletier";}
if (isset($_POST['phone']))
{
$remarks = sanitizeOne(get_post('phone'), 'plain');
}
else
{$phone = "201.710.5500";}
if ($submitted) {
$query = 'PREPARE statement FROM "INSERT INTO bix(area, price, address, bedrooms,
fullbath, halfbath, sqft, remarks, realtor, phone) VALUES(?,?,?,?,?,?,?,?,?,?)"';
mysql_query($query);
$query = 'SET
#area = "' . $area . '"' .
'#price = "' . $price . '"' .
'#address = "' . $address . '"' .
'#bedrooms = "' . $bedrooms . '"' .
'#fullbath = "' . $fullbath . '"' .
'#halfbath = "' . $halfbath . '"' .
'#sqft = "' . $sqft . '"' .
'#remarks = "' . $remarks . '"' .
'#realtor = "' . $realtor . '"' . //line 255
'#phone = "' . $phone . '"'; //line 256
mysql_query($query);
$query = 'EXECUTE statement USING #area,#price,#address,#bedrooms,#fullbath,#halfbath,#sqft,#remarks,#realtor,#phone';
mysql_query($query);
$query = 'DEALLOCATE PREPARE statement';
mysql_query($query);
return true;
}
}
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
This is simply adding an entry to a database if it was submitted (the page submits a form to itsself to do this)

Your problem is here, a cut'n'paste error;
if (isset($_POST['realtor']))
{
$remarks = sanitizeOne(get_post('realtor'), 'plain');
}
else
{$realtor = "Anne-Marie Pelletier";}
If realtor is set as a post parameter, you assign the post variable's value to $remarks instead of to $realtor.
$phone has the exact same problem.

If the phone value was passed you are setting the remarks variable to the phone content, if its not set you are setting the fixed phone
change:
if (isset($_POST['phone']))
{
$remarks = sanitizeOne(get_post('phone'), 'plain');
}
else
{$phone = "201.710.5500";}
to
if (isset($_POST['phone']))
{
$phone = sanitizeOne(get_post('phone'), 'plain');
}
else
{$phone = "201.710.5500";}
Same for the realtor
To debug the all-null problem, try to record a record without realtor or phone i.e. using the defaults in code. if you get those two values stored, then the problem is in santizeOne, post the code to that for us to help. If its not try to capture the output of all the first to queries and post it.

You are never assigning anything to $realtor or $phone.
if (isset($_POST['realtor']))
{
$remarks = sanitizeOne(get_post('realtor'), 'plain');
}
you probably mean to use $realtor = sanitizeOne(get_post('realtor'), 'plain');
same for $phone.

Related

Adding data to PostgreSQL via form. Add fails if variable null/empty, how do I prevent this?

I'm adding data to a PostgreSQL database via a PHP form. It all feels a bit sketchy. My main concern is that; in the event of a variable being null/empty the add fails. How do I prevent this?
The simplified code is like this:
$name = $_POST['name'];
$movie = $_POST['movie'];
$query = "INSERT INTO data.base(name, movie) VALUES('" . $name . "', '" . $movie . "')";
$result = pg_query($query);
if ( $result ) {
echo 'Thanks';
} else {
echo 'Error';
}
So if the $movie variable is null/empty the whole add fails.
I could do something like this I suppose:
$name = $_POST['name'];
if ( ! $name ) {
$name = '0';
}
But I'd rather keep the cell empty as opposed to inserting false data.
Any help would be much appreciated.
PHP 7+ is required for my solution.
If your name and movie column can be null, and devault value is null you can do something like this:
$name = $_POST['name'] ?? null;
$movie = $_POST['movie'] ?? null;
$query = "INSERT INTO data.base(name, movie) VALUES('" . $name . "', '" . $movie . "')";
$result = pg_query($query);
if ( $result ) {
echo 'Thanks';
} else {
echo 'Error';
}
unfortunatelly it will be an empty row in you table.
But if you don't want junk rows, do something like this:
$name = $_POST['name'] ?? false;
$movie = $_POST['movie'] ?? false;
if ( $name and $movie ) {
$query = "INSERT INTO data.base(name, movie) VALUES('" . $name . "', '" . $movie . "')";
$result = pg_query($query);
echo 'Thanks';
} else {
echo 'Error';
}
I recommend you to escaping the inputs.

The Filename of the image I'm uploading is not changing

Evertime I upload a picture, the FILENAME is NOT CHANGING the static value(filename) that is inserting in database is always "0.png" I don't know how is that happening, Please Help me how to fix this problem.
Here is my code:
<?php
session_start();
include("../db_connection.php");
$seller_id = $_SESSION['seller_id'];
$trade_name = $_POST ['trade_name'];
$s_address = $_POST ['s_address'];
$opening_time = $_POST ['opening_time'];
$opening_days = $_POST ['opening_days'];
$order_cutoff = $_POST ['order_cutoff'];
$seller_delivery_time = $_POST ['seller_delivery_time'];
$area_covered_delivery = $_POST ['area_covered_delivery'];
$delivery_fee = $_POST ['delivery_fee'];
$extension = pathinfo($_FILES['s_image']['name'], PATHINFO_EXTENSION);
$sql = mysqli_query($db, "UPDATE selling_details
SET
opening_time = '$opening_time',
opening_days = '$opening_days',
order_cutoff = '$order_cutoff',
seller_delivery_time = '$seller_delivery_time',
area_covered_delivery = '$area_covered_delivery',
delivery_fee = '$delivery_fee'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql)
{
$id = mysqli_insert_id($db);
$filename = $id.'.'.$extension;
if(move_uploaded_file($_FILES['s_image']['tmp_name'], 'upload/'.$filename))
{
$sql2 = mysqli_query($db, "UPDATE seller
SET
trade_name = '".$trade_name."',
s_address = '".$s_address."',
s_image = '".$filename."'
WHERE seller_id= '" . $_SESSION['seller_id'] . "' ");
if ($sql2)
{
header('location: seller_menu.php');
}
else
{
echo "error occured : " . mysqli_error($db);
}
}
else
{
echo "error occured : " . mysqli_error($db);
}
}
?>
The function mysqli_insert_id returns the id of the row you just inserted into your database, and since you don't insert anything (you just update) the value the function returns is 0, so the name of your image is $id.'.'.$extension ==> 0.png.
Since you update the seller_id, and you have it inside $_SESSION['seller_id'], you can use it in your code:
$filename = $_SESSION['seller_id'].'.'.$extension;

How to prevent data being sent to the database if fields are empty?

How would I go about not sending the data to the database if the some of the fields are left empty? Right as of now, if a field is empty on the form, the database is replacing whatever was in the field with blank data
UPDATE: Forgot to mention, it doesn't matter if the some of the fields are left blank, that should be allowed.
My code
<?php
if (isset($_POST['eventname'], $_POST['date'], $_POST['eventvenue'] , $_POST['eventtime'], $_POST['eventcost'])){
$eventname = ($_POST['eventname']);
$eventdate = ($_POST['date']);
$eventtime = ($_POST['eventtime']) . ":00";
$eventvenue = ($_POST['eventvenue']);
$eventcost = ($_POST['eventcost']);
$result = mysql_query("UPDATE event set event_name = '" . $eventname . "', event_date = '" . $eventdate . "', event_time = '" . $eventtime . "', event_venue = '" . $eventvenue ."', event_cost = '" . $eventcost ."'");
}
?>
Try some thing like This
$query= "UPDATE event set ":
If(isset($var1)){
$query.= " var1=".$var1;
}else if (isset($var2)){
$query.= " var2=".$var2;
}
and so forth and then
$result = mysql_query($query);
You can read on PHP's function empty()
empty() on PHP.net
Example usage:
if(empty($eventname))
{
echo "You have not set event name";
} else {
mysqli_query(...);
}
As said on comments, do not use the deprecated mysql_* functions, use either mysqli_* or PDO.
This is an example using prepared statements; it builds the update statement based on whether the field is empty (zero length) or not.
Afterwards, the prepared statement is executed.
$updates = [];
$parameters = [];
if (strlen($_POST['eventname'])) {
$updates[] = 'event_name = ?';
$parameters[] = $_POST['eventname'];
}
// ...
if (strlen($_POST['eventtime'])) {
$updates[] = "event_time = ?";
$parameters[] = $_POST[$field] . ':00';
}
if ($updates) {
$sql = sprintf('UPDATE event SET %s WHERE xxx', join(',', $updates));
$stmt = $db->prepare($sql);
$stmt->execute($parameters);
}

Why is this code returning a line break before the echo?

So I have this login php script that I am using and it works fine on one server (returns "success" || "invalid login") and then this other server it breaks because it returns a line break and then "success" or "invalid login"
My guess is a php.ini setting. I am just not sure which one.
<?php
include("../config.php");
include("../connect.php");
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
echo "success";
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
echo "success";
}
else
{
echo "invalid login";
}
}
?>
I'd bet you a coke that connect.php or config.php contain a \n (or \r\n) before or after their <?php ?> parts.
This is most likely due to your includes. The code you posted has no reason to have one, and there is no php.ini setting that I'm aware of to add such.
Post your config and connect (with username/pw hidden) for us to help further.
The code displayed does not indicate the occurrence of a line-break.
On a side note since you are only outputting one value from your booleans then you could initialize a variable to hold the response and then only echo the response once:
<?php
include("../config.php");
include("../connect.php");
$response = 'success';
$adminCheck = mysql_query("SELECT * FROM admins WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($adminCheck) == 1)
{
$result = mysql_fetch_array($adminCheck);
$_SESSION['user']['level'] = "admin";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
}
else
{
$clientCheck = mysql_query("SELECT * FROM clients WHERE username = '" . mysql_real_escape_string($_POST['username']) . "' AND password = '" . mysql_real_escape_string($_POST['password']) . "'");
if (mysql_num_rows($clientCheck) == 1)
{
$result = mysql_fetch_array($clientCheck);
$_SESSION['user']['level'] = "client";
$_SESSION['user']['userid'] = $result['id'];
$_SESSION['user']['username'] = $result['username'];
$_SESSION['user']['client'] = $result['client'];
}
else
{
$response = "invalid login";
}
}
echo $response;
?>

Variable losing its value

I looked through the stack questions and answers, but didn't see anything I could directly apply here. Maybe I'm just missing something.
The code below works fine, except when I include my where statement which refers to the value of the $wp_user_id variable.
I've checked that the variable IS actually being populated with a $user_id when the script is loaded. It appears that the value of this variable is lost right after the call to the conManager function, but I don't understand why. There doesn't appear to be anything within the ConnectionManager.php file (which defines the conManager function) which would touch this variable, so I'm at a loss.
I'm a PHP hack, so go easy on me, but what is causing me to lose the value of my variable, and how do I address it? Here's the code:
<?php
include_once("/home/evaluate/public_html/admin/php/ConnectionManager.php");
header('Content-type:text/javascript;charset=UTF-8');
$wp_user_id = $_GET["user"];
$json1=json_decode(stripslashes($_POST["_gt_json"]));
$pageNo = $json1->{'pageInfo'}->{'pageNum'};
$pageSize = $json1->{'pageInfo'}->{'pageSize'};
if(isset($json1->{'sortInfo'}[0]->{'columnId'})){
$sortField = $json1->{'sortInfo'}[0]->{'columnId'};
}
else{
$sortField = "miles_on_oil";
}
if(isset($json1->{'sortInfo'}[0]->{'sortOrder'})){
$sortOrder = $json1->{'sortInfo'}[0]->{'sortOrder'};
}
else{
$sortOrder = "ASC";
}
if($json1->{'sortInfo'}[0]->{'sortOrder'} == "defaultsort"){
$sortField = "miles_on_oil";
$sortOrder = "ASC";
}
if($json1->{'filterInfo'}[0]->{'value'} != "") {
for ($i = 0; $i < count($json1->{'filterInfo'}); $i++) {
if($json1->{'filterInfo'}[$i]->{'logic'} == "equal"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "notEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "!='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "less"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "lessEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "great"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "greatEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "like"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "startWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "endWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == ""){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}
$filter .= " AND ";
}
}
else {
$filter = '';
}
//print_r ($json1);
//die;
// Temp TEsting Values
// End Temp Testing Values
$conManager = new ConManager();
$conManager->getConnection();
if($json1->{'action'} == 'load'){
//to get how many records totally.
$sql = "select count(*) as cnt from oil_analysis_data where $filter user_id = '".$wp_user_id."'";
$handle = mysql_query($sql);
$row = mysql_fetch_object($handle);
$totalRec = $row->cnt;
$sql2 = "select * from oil_analysis_data where $filter user_id = '".$wp_user_id."' ORDER BY " . $sortField . " " . $sortOrder . " limit " . ($pageNo - 1)*$pageSize . ", " . $pageSize;
$handle2 = mysql_query($sql2);
$retArray2 = array();
while($row2 = mysql_fetch_assoc($handle2)) {
// Grab Vehicle Make, Model & Year "Names" from their respective tables & insert into the array
$year = "select Name from vehicle_data_years where ID = {$row2['list1']}";
$year1 = mysql_query($year);
$year2 = mysql_fetch_assoc($year1);
$year3 = $year2['Name'];
$make = "select Name from vehicle_data_makes where ID = {$row2['list2']}";
$make1 = mysql_query($make);
$make2 = mysql_fetch_assoc($make1);
$make3 = $make2['Name'];
$model = "select Name from vehicle_data_all where ID = {$row2['list3']}";
$model1 = mysql_query($model);
$model2 = mysql_fetch_assoc($model1);
$model3 = $model2['Name'];
$row2['list1'] = $year3;
$row2['list2'] = $make3;
$row2['list3'] = $model3;
// Grab Motor oil Viscosity, Brand & Product "Names" from their respective tables & insert into the array
$visc = "select name from viscosity where id = {$row2['viscosity']}";
$visc1 = mysql_query($visc);
$visc2 = mysql_fetch_assoc($visc1);
$visc3 = $visc2['name'];
$brand = "select brandname from oil_brand where brandid = {$row2['brand']}";
$brand1 = mysql_query($brand);
$brand2 = mysql_fetch_assoc($brand1);
$brand3 = $brand2['brandname'];
$product = "select product_name from oil_data where id = {$row2['product']}";
$product1 = mysql_query($product);
$product2 = mysql_fetch_assoc($product1);
$product3 = $product2['product_name'];
$row2['viscosity'] = $visc3;
$row2['brand'] = $brand3;
$row2['product'] = $product3;
if($row2['bypass_filtration'] == 1) {
$row2['bypass_filtration'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['bypass_filtration'] = "";
}
if($row2['oil_change'] == 1) {
$row2['oil_change'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['oil_change'] = "";
}
$retArray[] = $row2;
}
$analysis_data = json_encode($retArray);
$ret = "{data:" . $analysis_data .",\n";
$ret .= "pageInfo:{totalRowNum:" . $totalRec . "},\n";
$ret .= "recordType : 'object'}";
echo $ret;
}
?>
I'm curious, why do you add a semi colon after the $wp_user_id; ? I've noticed you doing this in more than one place. This may be the culprit.
$filter user_id = '".$wp_user_id;."'";
Nevermind. It would appear that my problem actually resulted from a change in my code that I had forgotten about. I changed $_REQUEST['user'] to $_GET['user'], thinking that, in this case, since the value was being passed as a URL query string, that wouldn't be a problem.
To be honest, I'm still not entirely sure why that made a difference - although I can research that on my own. But, at any rate, changing that back corrected my problem entirely.
Thanks to those who responded, though. Even if not solutions to my actual problem, the information from both turned out to be very useful.
Any hacker can severely screw up or delete your database because of the way you use direct user provided data to build up your SQL query. Please instead read up on SQL Injection, and the use of PHP prepared statements.
Relevant

Categories