Echo a function variable in PHP - 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.

Related

Php view photo by id

Hi i have an address book I added the possibility of add a photo.
This is the function for view Name,Surname,Email and telephone
// Display users
public function display(){
$temp_arr = array();
$res = $this->db->run("SELECT * FROM users ORDER by cognome,nome ");
$count=$this->db->rowCount();
while($row = $this->db->fetchArray()) {
$temp_arr[] =$row;
}
return $temp_arr;
}
<?php
$data = $user->display();
$i = 0;
foreach( $data as $eachrecord ) {
$i++;
?>
my idea was to do so how do i implement it?
$sql = "SELECT name FROM upload where id=$id";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$image = $row['name'];
$image_src = "uploads/".$image;
<td><img src='<?php echo $image_src; ?>' ></td>
to take id use this function
// get id upload
public function getid(){
$db = new mysqli("localhost","root","", "rubrica");
if ($db-> connect_errno) {
exit();
}
$nome = $this->unome;
$cognome = $this->ucognome;
$email = $this->uemail;
$telefono = $this->utel;
$query = $db->query("SELECT id FROM users WHERE nome='$nome' and cognome='$cognome' and email='$email' and telefono='$telefono'");
$id = $query->fetch_assoc()['id'];
$db->close();
return $id;
}
thank you in advance who will help me!

How does one pass the properties of a $_POST to a Function?

I would like to pass the properties to a function to Update details in a database. I want all the columns that were selected in the form to be passed to a function. Frankly, I don't know what to do.
My code is the following:
if (isset($_POST["updateWineButton"])) {
$wineID = $_POST["wineID"];
$wineCountryID = $_POST["wineCountryID"];
$wineSizeID = $_POST["wineSizeID"];
$wineRatingID = $_POST["wineRatingID"];
$wineColourID = $_POST["wineColourID"];
$packageID = $_POST["packageID"];
$wineCategoryID = $_POST["wineCategoryID"];
$wineCode = $_POST["wineCode"];
$price = $_POST["price"];
$description = $_POST["description"];
$wineRating = $_POST["wineRating"];
$wineIMG = $_POST["wineIMG"];
updateWine($updateWine);
$status = "$description has been updated.";
}
Update Wine Function
function updateWine($wineUpdate)
{
global $pdo;
$statement = $pdo->prepare("UPDATE WINE SET wineID=?, wineCountryID=?, wineSizeID=?, wineRatingID, wineColourID=?,
packageID=?, wineCategoryID=?, wineCode=?, price=?, description=?, wineRating=?, wineIMG=?
WHERE wineID=?");
$statement->execute([$wineUpdate->wineID,
$wineUpdate->wineCountryID,
$wineUpdate->wineSizeID,
$wineUpdate->wineRatingID,
$wineUpdate->wineColourID,
$wineUpdate->packageID,
$wineUpdate->wineCategoryID,
$wineUpdate->wineCode,
$wineUpdate->price,
$wineUpdate->description,
$wineUpdate->wineRatingID,
$wineUpdate->wineIMG]);
$statement->fetch();
}
Something like the following should work for you:
function updateWine()
{
global $pdo;
$keys = [
"wineID", "wineCountryID", "wineSizeID", "wineRatingID", "wineColourID", "packageID", "wineCategoryID",
"wineCode", "price", "description", "wineRating", "wineIMG",
];
$results = [];
foreach ($keys as $index) {
if (isset($_POST[$index])) {
$results[$index] = $_POST[$index];
}
}
$statement = $pdo->prepare("UPDATE WINE SET " . implode('=?, ', array_keys($results)) . "=? WHERE wineID =?");
$statement->execute(array_merge(array_values($results), [$_POST['wineID']]));
$statement->fetch();
}
if (isset($_POST["updateWineButton"]) && isset($_POST['wineID'])) {
updateWine();
}
Hope this helps!
if I understand correctly you want to do something like this,
if (isset($_POST["updateWineButton"])) {
$result = updateWine($_POST);
if($result){
$status = "$description has been updated.";
}else{
$status = "An error occurred.";
}
}
//your function woud then look like ...
function updateWine($postdata){
$wineID = $postdata["wineID"];
$wineCountryID = $postdata["wineCountryID"];
$wineSizeID = $postdata["wineSizeID"];
$wineRatingID = $postdata["wineRatingID"];
$wineColourID = $postdata["wineColourID"];
$packageID = $postdata["packageID"];
$wineCategoryID = $postdata["wineCategoryID"];
$wineCode = $postdata["wineCode"];
$price = $postdata["price"];
$description = $postdata["description"];
$wineRating = $postdata["wineRating"];
$wineIMG = $postdata["wineIMG"];
//udpate your database with the above values
//check if update is successful
return true;
//else if there was an error
return false;
}

cannot display 0 value in an html textbox

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.

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.

How can i return more than 1 values from a foreach loop using PHP

Here's my function
function GetUser($id)
{
global $pdo;
$stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
$stmt->execute(array(':id'=>$id));
foreach($stmt as $name){
$lname = $name['lname'];
$lname = $name['fname'];
$mi = $name['mi'];
}
return //what to put here?
}
Here's my code to use the function
include 'function.php';
$names = GetUser($_SESSION['id']);
//what's next?
How can i retrieve the $lname,$fname and $mi from the function? Need any help and suggestions. Thank you :)
For starters don't use the global keyword, but inject the variable you need. Second why don't you return an array?:
function getUser($pdo, $id)
{
$stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
$stmt->execute(array(':id'=>$id));
$result = array();
foreach($stmt as $name){
$result['lname'] = $name['lname'];
$result['fname'] = $name['fname'];
$result['mi'] = $name['mi'];
}
return $result;
}
$result = getUser($pdo, 1);
var_dump($result);
Note that this will only return the last result. If you want it all:
function getUser($pdo, $id)
{
$stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
$stmt->execute(array(':id'=>$id));
return $stmt->fetchAll();
}
$result = getUser($pdo, 1);
var_dump($result);
Also note that I have made your function name starting with a normal letter instead of a capital. The "normal" naming convention is that classes start with a capital, but function / methods with a normal one.
If you want to retrieve the information based on the first solution you would do:
echo $result['lname'];
If you want to retrieve the information based on the second solution you would do:
echo $result[0]['lname'];
function GetUser($id)
{
global $pdo;
$stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
$stmt->execute(array(':id'=>$id));
foreach($stmt as $name){
$lname = $name['lname'];
$lname = $name['fname'];
$mi = $name['mi'];
}
return array(
"$lname" => $lname,
"$fname" => $fname,
"$mi" => $mi
);
}
This is what's next part:
include 'function.php';
$myArray = GetUser($_SESSION['id']);
$fname = $myArray["$fname"];
$lname = $myArray["$lname"];
$mi = $myArray["$mi"];
Or:
include 'function.php';
$myArray = GetUser($_SESSION['id']);
$fname = $myArray[0];
$lname = $myArray[1];
$mi = $myArray[2];
return array(
"lname" => $lname,
"fname" => $fname,
"mi" => $mi
);
function GetUser($id) {
global $pdo;
$stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
$stmt->execute(array(':id'=>$id));
return $stmt;
}
include 'function.php';
$names = GetUser($_SESSION['id']);
foreach($names as $name){
$lname = $name['lname'];
$lname = $name['fname'];
$mi = $name['mi'];
}
Not tested, but I think it should work
function GetUser($id)
{
global $pdo;
$stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
$stmt->execute(array(':id'=>$id));
return count($stmt)==1?$stmt[0]:null; //you may have nothing returned from the database so return null
}
Then:
include 'function.php';
$names = GetUser($_SESSION['id']);
if ($names){ //if this is not null then get the properties
echo $names['fname'];
echo $names['lname'];
echo $names['mi'];
}

Categories