cannot display 0 value in an html textbox - php

I'm displaying data from mysql using php.
You can see the value is 0 for Current Balance
But in edit mode it cant display 0
Before executing update statement
I declare its variable from its corresponding $_POST variable
if (!empty($_POST)) {
$ID = $_POST['ID'];
$Name = $_POST['Name'];
$AID = $_POST['AID'];
$CurrentBalance = $_POST['CurrentBalance'];
$valid = true;
if ($valid) {
$setsu = dbSetsuzoku();
$setsu->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE tabledb SET ID = ?, Name = ?, AID=?, CurrentBalance=? WHERE SubAgentID = ?";
$q = $setsu->prepare($sql);
$q->execute(array($ID,$Name,$AID,$CurrentBalance,$ID));
$setsu = null;
}
}
else {
$setsu = dbSetsuzoku();
$setsu->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM tabledb where ID = ?";
$q = $setsu->prepare($sql);
$q->execute(array($ID));
$data = $q->fetch(PDO::FETCH_ASSOC);
$ID = $data['ID'];
$Name = $data['Name'];
$AID = $data['AID'];
$CurrentBalance = $data['CurrentBalance'];
$setsu = null;
}
html (edit mode)
<input name="CurrentBalance" type="text" placeholder="CurrentBalance" value="<?php echo !empty($CurrentBalance)?$CurrentBalance:'';?>" required />
other fields follow the same logic

The problem is :
<?php echo !empty($CurrentBalance)?$CurrentBalance:'';?>
For empty function 0 is considered as empty - just look at http://au2.php.net/manual/en/function.empty.php
You can change it into:
<?php echo isset($CurrentBalance)?$CurrentBalance:'';?>

If you check the documentation of empty() function, you'll see that it will give back true for 0. Because of this you just display an empty string here:
<input name="CurrentBalance" type="text" placeholder="CurrentBalance" value="<?php echo !empty($CurrentBalance)?$CurrentBalance:'';?>" required />
Simple solution is to change the empty stirng to 0.

Related

How do I ensure null is sent instead of 0 for empty form fields

I have a table with columns that allow null values and has a default null value. On update, if the field is empty (not data inserted) my script inserts 0 instead of null. I have gone through similar questions as mine and i have tried the advice given but am still not able to fix my issue. Here's my code
<?php
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = null;} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = null;} else {$test3 = $_POST["test3"];}
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
$test_1 = mysqli_real_escape_string($connection, $test1[$i]);
$test_2 = mysqli_real_escape_string($connection, $test2[$i]);
$test_3 = mysqli_real_escape_string($connection, $test3[$i]);
$query = "UPDATE fullresult SET test1='{$test_1}', test2='{$test_2}', test3='{$test_3}' WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
?>
When i echo the query, this is what i see and am wondering why i still get 0 inserted
UPDATE fullresult SET test1=' 10', test2=' ', test3=' ' WHERE student_id=51 AND subject_id=2
is_null does not return true for an empty string. Try changing your if statements to something like this:
$test1 = trim($_POST["test1"])
if (!strlen($test1)) $test3 = null;
You could use
ctype_digit
to check if there are numeric characters in it.
The function
mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
(Source: http://php.net/manual/en/mysqli.real-escape-string.php)
Since you want to have null inside the database you should rewrite the code
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = mysqli_real_escape_string($connection, $_POST["test1"]);}
to have the values escaped only if needed (which is in case you have a value in $_POST)
What about
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
# only retrieve FILLED IN answers
$tests = array();
if(isset($_POST["test1"]) && strlen($_POST["test1"])) $tests['test1'] = $_POST["test1"];
if(isset($_POST["test2"]) && strlen($_POST["test2"])) $tests['test2'] = $_POST["test2"];
if(isset($_POST["test3"]) && strlen($_POST["test3"])) $tests['test3'] = $_POST["test3"];
if(!empty($tests)){ # if there were no answers, there's no point in updating the database
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
# now let's build the "SET" part of the query
$set = array();
foreach($tests as $key => $value) $set[]=mysqli_real_escape_string($key)."='".mysqli_real_escape_string($value)."'";
$set = implode(', ',$set);
# ...and finally update
$query = "UPDATE fullresult SET {$set} WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
}
The point of this approach is that if you don't include a key=>value pair in your UPDATE query, it will be filled in with its default value.
You must set 'null' word, not null value.
if (is_null($_POST["test1"])){$test1 = 'null';} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = 'null';} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = 'null';} else {$test3 = $_POST["test3"];}

PHP PDO Insert Into statement doesn't work with no errors

At the end of this code there is a INSERT INTO statement that doesn't do anything. My connection.php is OK because I have used the same file in other projects and they work.
I am actually inserting a lot more data, but I was trying to find the problem out so I've removed a lot of variable from the INSERT statement.
<?php
include("connection.php");
include("functions.php");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
date_default_timezone_set('Asia/Dhaka');
$mobile = (string)$_GET["mobile_number"];
$promo = (string)$_GET["promo_code"];
$type = (string)$_GET["type"];
$type_no = (($type=="imei") ? (string)$_GET["imei"] : (string)$_GET["udid"]);
$ip = (string)$_SERVER['REMOTE_ADDR'];
$signup_date = date("Y-m-d");
$q1 = "SELECT * FROM vbClient WHERE clCustomerID = :mobile";
$chk_mob_switch = $dbh->prepare($q1);
$chk_mob_switch->bindParam(':mobile', $mobile);
$chk_mob_switch->execute();
if ($chk_mob_switch->rowCount() == 0) {
$q2 = "SELECT * FROM api_db WHERE type_no = :type_no";
$chk_imei_bknd = $dbh->prepare($q2);
$chk_imei_bknd->bindParam(':type_no', $type_no);
$chk_imei_bknd->execute();
if ($chk_imei_bknd->rowCount() == 0) {
$validation_code = (string)generateValidationCode(6);
$request_id = (string)generateRequestID(15);
$q3 = "INSERT INTO api_db (mobile) VALUES (:mobile)";
$ins_info_bknd = $dbh->prepare($q3);
$ins_info_bknd->bindParam(':mobile', $mobile);
$ins_info_bknd->execute();
}
To check for errors I am using a function like the following:
function chkSyntax($dbh, $stmt, $query) {
$stmt = $dbh->prepare($query);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
}
And then I'm calling it like this:
chkSyntax($dbh, $chk_mob_switch, $q1);
What am I doing wrong?

Echo a function variable in PHP

I am trying to use a variable from my function in an echo in PHP for a form. This is an update form so I want to display current user informatoin.
My function is like this:
public static function current()
{
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
$pdo = Database::connect();
$sql = "SELECT * FROM customer where counter = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
$firstname = $data['firstname'];
$lastname = $data['lastname'];
$email = $data['email'];
Database::disconnect();
}
my form is trying to echo it here in the value:
<input class="form-control" name="firstname" id="firstname"
value="<?php echo !empty($firstname)?$firstname:'';?>">
I can't seem to get the $firstname variable to echo the users first name. The user is called by a string in the url that uses ?id=
Two options,
return the desired value (or values) from the function
public static function current()
{
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
$pdo = Database::connect();
$sql = "SELECT * FROM customer where counter = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
Database::disconnect();
return array_intersect_key($data, array_flip(array('firstname', 'lastname', 'email')));
}
...
$user = Thing::current();
echo $user['email'];
OR set a static variable in your class to reference after
public static function current()
{
$id = null;
if ( !empty($_GET['id'])) {
$id = $_REQUEST['id'];
}
$pdo = Database::connect();
$sql = "SELECT * FROM customer where counter = ?";
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
self::$firstname = $data['firstname'];
self::$lastname = $data['lastname'];
self::$email = $data['email'];
Database::disconnect();
}
...
echo Thing::$firstname;
I'd prefer the first thing, but instead of returning an array with the details, make it into a Customer object.

select value into variable using input from form

Hi i am having an issue selecting a value form my table into a variable in the PHP so that I can calculate the cost of something
here is the code I have so far I want to be able to select a "cost" value from the table C_price where the values of I_type and a_type match
E.g. the table structure looks like this
ID=1,A_type=line,I_type=Head,cost=5
if on the form i enter line and head
i need to be able to get the value 5 in to a venerable i can use in calculations and insert into another table AKA i need to get cost into a variable somehow
the following was my try and i need help im new at all this so please help
$E_C;
$T_cost = "1";
$date = date("d.m.y");
$name = $_POST["from"];
$email = $_POST["email"];
$ref = $_POST["link"];
$i_type = $_POST["i_type"];
$a_type = $_POST["a_type"];
$extra = $_POST["extra"];
$des = $_POST["description"];
$BG = $_POST["BG"];
$bg_type = $_POST["BGtype"];
$msg = $_POST["message"];
$auto_reply = ("thanks for the email we will get back to you as soon as we can about the cost and how you can pay");
$msg = wordwrap($msg, 70);
$host = "localhost";// hostname
$USER = "root";// username
$PASS = "Password";// password
$DBNAME = "andrea";// databace name
$tbl_name = "c_price";// table name
$con = mysqli_connect("localhost", $USER, $PASS, $DBNAME)or die("mySQL server connection failed");
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
$result = mysqli_query($con,$all) or die("Error getting total storse");
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
if ($a_type = 'waist' && $extra='Y')
{
$E_C = $cost * .3;
}
elseif ($a_type = 'knee' && $extra='Y')
{
$E_C = $cost * .35;
}
elseif ($a_type ='full' && $extra='Y')
{
$E_C = $cost * .4;
}
else
{
$E_C = 0;
}
$T_cost = $cost + $E_C;
if ($BG = 'y')
{
$T_cost = $T_cost + 10;
}
You can't use mysqli and mysql at a same time.. Mysqli is a class... So first change that things...
while($row = mysqli_fetch_array($result))
{
echo $row['cost'];
}
$news1 = mysqli_result($result, 0); // 0 is the index of the field, not the row
echo $news1;
echo $cost;`
Query should be like this...
$all = "SELECT cost FROM C_price WHERE a_type='$a_type'and i_type='$i_type'";
You cant mix mysql and mysqli
change this line In the while loop and add for error mysqli_error
$news1 = mysql_result($result, 0);
$news1 = mysqli_result($result) or die(mysqli_error());
and your query is wrong as well and A_type is not same as A_type and same goes for I_type as well
$all = "SELECT cost FROM C_price WHERE a_type=$a_type,i_type=$i_type";
//Change it to
$all = "SELECT cost FROM C_price WHERE A_type='$a_type'and I_type='$i_type'";
//and A_type is not same as a_type and same goes for I_type as well

PDO CRU are not functioning

I need your help figuring this out. I am trying to have a reserve a book functionality in my project. I don't have any error with this one but my oop functions that contains the pdo statements won't work. Particulary with the insert (values can't be inserted into the database) and update(can't update existing info from the database) part. I don't know why this happens.
bookReserve.php
<?php
session_start();
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex_books();
$sname = $_POST['sname'];
$sid = $_POST['sid'];
$id = $_POST['id'];
$title = $_POST['title'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$publisher = $_POST['publisher'];
$language = $_POST['language'];
$genre = $_POST['genre'];
$quantity = $_POST['quantity'];
$date_to_be_borrow = $_POST['date_to_be_borrow'];
$result = $code->bookreserve($id,"book_info");
if(isset($_POST['reserve']))
{
foreach($result as $row)
{
echo $oldstock=$row['quantity'];
}
echo $newstock = $oldstock-1;
$code->minusbookreserve($quantity, $newstock,"book_info");
$code->insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,"reserve_list");
// echo "<script type='text/javascript'>alert('Successfully Reserved.');window.location='bookReservelist.php';</script>";
}
else {
echo "<script type='text/javascript'>alert('Something went wrong.');window.location='bookReservelist.php';</script>";
}
?>
codex_books.php
public function minusbookreserve($quantity, $newstock, $table)
{
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
if($stmt){
return true;
}
else {
return false;
}
}
public function insertbookreserve($sid,$sname,$title,$author,$isbn,$publisher,$language,$genre,$quantity,$date_to_be_borrow,$table)
{
$q = "INSERT INTO $table SET sid= :sid ,sname=:sname,title=:title,author=:author,isbn=:isbn,publisher=:publisher,language=:language, genre=:genre, quantity=:quantity, date_to_be_borrow=:date_to_be_borrow";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':sid'=>$sid,':sname'=>$sname,':title'=>$title,':author'=>$author,':isbn'=>$isbn,':publisher'=>$publisher,':language'=>$language, ':genre'=>$genre,':quantity'=>$quantity,':date_to_be_borrow'=>$date_to_be_borrow));
return true;
}
Given:
$q = "UPDATE $table SET quantity = ':newstock' where book_title = ':book_title'";
^^^^^^^^^^^
Where's book_title here?
$stmt->execute(array(':newstock'=>$newstock, ':quantity'=>$quantity));
You really MUST check return values from your DB calls for boolean FALSE, indicating failure. You're simply assuming everything will always succeed, which is a very BAD way of writing code.

Categories