PHP: call a string from another page function? - php

Can you do that? I just tried but it doesnt seem to work.
I have dbc.php included at top of my page, and in dbc.php at the bottom i created this function:
function getUserInfo($id) {
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$showUR = mysql_fetch_array($thaString);
$showURP = mysql_fetch_array($thaString2);
}
So it would be easier for me to call them instead of running the queries all the time when i need them in other pages..
But when i try to do:
getUserInfo($showInfo["bID"]);
echo $showUR["full_name"];
I dont get any result, is there a smarter way to do this, if so how?

It's an issue of scope: $showUR is set inside getUserInfo(), so it's not available to the echo outside the function. There are lots of potential modifications you could make, but you may want to assign your values into an array and then return that array:
function getUserInfo($id) {
$user = array();
$thaString = mysql_query("SELECT * FROM users WHERE id = '$id'");
$thaString2 = mysql_query("SELECT * FROM users_profile WHERE uID = '$id'");
$user['showUR'] = mysql_fetch_array($thaString);
$user['showURP'] = mysql_fetch_array($thaString2);
return $user;
}
$user = getUserInfo($showInfo["bID"]);
echo $user['showUR']["full_name"];

Your functions have to return something for the values to be used, or $showUR and $showURP will just get lost once the function exits (ie: the scope will change). Something like:
function someFunc($arg) {
return "Hello, I am {$arg}";
}
$showUR = someFunc('name');
echo $showUR;
And please don't call stuff $thaString. First because it's a misnomer (mysql_query() doesn't return a string, it returns a resource or a boolean), Second because "tha" is so lame.

Let your function return the variable.
And then use $showUR = getUserInfo(...)

If you declare them outside the function, and then as globals inside the function you should be able to use them as you are now.

Related

Variable invisible outside a function

I have written a query to get customer information from my database but say I want to use it on another page. I don't want to have to copy and paste to the other page to use it.
I have looked at a function but I don't know how to get the variables out of the function.
This is my current function:
function getCustomer($customerid) {
$getcustomer = mysql_query("SELECT * FROM hire_customers WHERE id='".$customerid."'");
$fetch = mysql_fetch_assoc($getcustomer);
$cust_firstname = $fetch['firstname'];
$cust_lastname = $fetch['lastname'];
$cust_address = $fetch['address'];
$cust_town = $fetch['town'];
$cust_postcode = $fetch['postcode'];
$cust_cont1 = $fetch['contact1'];
$cust_number1 = $fetch['contactnumber1'];
$cust_cont2 = $fetch['contact2'];
$cust_number = $fetch['contactnumber2'];
$cust_email = $fetch['email'];
$cust_idform1 = $fetch['idform1'];
$cust_idnfo1 = $fetch['idinfo1'];
$cust_idform2 = $fetch['idform2'];
$cust_idinfo2 = $fetch['idinfo2'];
$cust_enterdby = $fetch['enteredby'];
}
This is my customer page
getCustomer($customerid);
echo $cust_firstname;
but nothing is echoed out.
Do I need to be looking at a class or object to do this? Have I gone wrong with my function.
What I would like to do is have a PHP file with all my customer functions (update, select, etc) in one place.
I think you should just return $fetch and then access it as a variable outside of the function.
function getCustomer($customerid) {
$customerid = mysql_real_escape_string($customerid);
$getcustomer = mysql_query("SELECT * FROM hire_customers WHERE id='".$customerid."'");
$fetch = mysql_fetch_assoc($getcustomer);
return $fetch;
}
$data=getCustomer($customerid);
echo data['firstname'];
This should get you started:
function getCustomer($customerid) {
$getcustomer = mysql_query("SELECT * FROM hire_.. etc");
$customer_data = mysql_fetch_assoc($getcustomer);
return $customer_data; // return here
}
$customer = getCustomer($customerid);
$cust_firstname = $customer['firstname'];
you need to return a value from your function return $variable;
In your code, variable $cust_firstname; is visible only inside that function.
Please read this: PHP variable scope
It works like this to reduce memory usage on web server - when function ends - variable is destroyed and memory freed.
Basically - you have to return that value somehow. Dave Chen wrote nice answer above/below, you can use his code.
BTW you can use extract(); function and reduce your code size and save a lot of time.
It works like this:
$fetch = mysql_fetch_assoc($getcustomer);
extract($fetch, EXTR_PREFIX_ALL, "cust_"); // creates variables from associative array
echo $cust_firstname; // magic! :)

Web browser is returning nothing - function error?

When I access this from a web browser it returns nothing other than echo'd text, I know this is similar to another question I posted but I can't make sense of it?
<?php
include('config.php');
include('database.php');
class conversion{
public $amnt;
public $cc_from;
public $cc_to;
public function __construct (){
$this->amnt = htmlspecialchars($_GET["amnt"]);
$this->cc_from = htmlspecialchars($_GET["from"]);
$this->cc_to = htmlspecialchars($_GET["to"]);
}
function convert($this->amnt,$this->cc_from,$this-cc_to,$decimals=2){
$db_rate_from = mysql_query("SELECT * FROM _currency WHERE country_code='$this- >cc_from'") or die(mysql_error());;
$query_row_from = mysql_fetch_array($db_rate_from);
$rate_from = ($query_row_from['rate']);
echo $rate_from;
echo "</br>rate to</br>";
$db_rate_to = mysql_query("SELECT * FROM _currency WHERE country_code='$this->cc_to'") or die(mysql_error());;
$query_row_to = mysql_fetch_array($db_rate_to);
$rate_to = ($query_row_to['rate']);
echo $rate_to;
echo "</br>conversion</>";
$conversion = (number_format(($amnt/$rate_from)*$rate_to,$decimals));
echo $conversion;
} }
$var = new conversion();
$var->convert($amnt,$cc_from,$cc_to);
?>
Given this:
$db_rate_from = mysql_query("SELECT * FROM $db_tbprefix WHERE country_code='$this->cc_from'");
where is $db_tbprefix defined? Nowhere, causing your query to be SELECT * FROM WHERE .... If you had proper SQL error handling code, this would've been clear to you. At absolute bare minimum, you should have something like:
$result = mysql_query("...") or die(mysql_error());
which would abort the script on a query failure and tell you exactly why the query failed.
As well, htmlspecialchars is NOT intended for database operations. It does absolutely nothing to prevent SQL injection. For that, you have to use mysql_real_escape_string().
One thing I notice is that you call your method without parameters.
$var->convert();
Yet it is declared to take three mandatory parameters.
function convert($amnt,$cc_from,$cc_to,$decimals=2)
And btw, don't use $query_row_to[rate]. Use either $query_row_to['rate'] or $query_row_to[$rate].
Edit:
How about something like this? Use global $db_tbprefix and skip object orientation.
<?php
include('config.php');
include('database.php');
function convert($amnt,$cc_from,$cc_to,$decimals=2) {
global $db_tbprefix;
$db_rate_from = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_from'") or die mysql_error();
$query_row_from = mysql_fetch_assoc($db_rate_from);
$rate_from = $query_row_from['rate'];
$db_rate_to = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_to'") or die mysql_error();
$query_row_to = mysql_fetch_assoc($db_rate_to);
$rate_to = $query_row_to['rate'];
return number_format(($amnt/$rate_from)*$rate_to,$decimals);
}
echo convert(floatval($_GET["amnt"]), mysql_real_escape_string($_GET["from"]), mysql_real_escape_string($_GET["to"]));
?>
Edit 2: only select what you need, in this case rate. And use mysql_fetch_assoc rather than than mysql_fetch_array which will double your memory consumption and slow down your code.
haven' tested it ... but the possibility i can find is you are passing parameters in function convert while defining it so you need to pass the same param while calling it... OR if the variables are the reference from the predefined one then use them like this
function convert($this->amnt,$this->cc_from,$this->cc_to,$decimals=2){
}

PHP convert session variable from array into int

I am storing session information in an array called 'Auth'. That array contains 2 session information: id and password. My problem is when I am using the id info for quering, it is not working. I am pretty sure it is due to the fact that the id info in my table is an int, and the one from the session array isn't. So my question is to know how to convert that session id variable into an int. Here below the function in which I am using $_SESSION(['Auth']['id']). Thank you in advance for your replies. Cheers. Marc
The PHP code where I am using the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
function isLogged(){
if(isset($_SESSION['Auth']) && isset($_SESSION['Auth']['id']) && isset($_SESSION['Auth']['pass'])){
extract($_SESSION['Auth']);
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = '$id' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
return true;
}
else{
return false;
}
}
}
?>
Here the PHP code where I set the session info:
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
require("connect.inc.php");
$identifiant = mysql_real_escape_string($_POST['identifiant']);
$pass = sha1($_POST['pass']);
$result = mysql_query("SELECT * FROM users WHERE usr_pseudo = '$identifiant' AND usr_pass = '$pass'");
if(mysql_num_rows($result)==1){
$data=mysql_fetch_assoc($result);
$_SESSION['Auth']=array(
'id'=>$data['usr_id'],
'pass'=>$pass
);
}
echo mysql_num_rows($result);
?>
extract() is a horribly ugly function, and you should wipe its existence out of your mind.
There's no need for it, since it's purely a holdover from PHP's early "lazy" days, when it tried to do everything for you, causing in part the miserable security reputation PHP has.
You can directly embed session variables wherever you want, even when it's an arbitrarily "deep" array reference like your session is:
$sql = "SELECT ... WHERE id={$_SESSION['Auth']['id']} ...";
or even
$id = $_SESSION['Auth']['id']'
$sql = "SELECT ... WHERE id=$id";
will both work the same way, and not litter your variable namespace with useless junk.
You can cast any variable into any type by using the cast methods.
$usr_id = (int)$data['usr_id']
This would return a type of integer. If the id includes anything else but integers, 0 is returned.
http://php.net/manual/en/language.types.type-juggling.php
You should not query DB each time you'd like to check if the user is logged in. And you don't need to store password in the seesion.
You have to query db only once when you login user (your second part of the code).
And it would be better if you create a simple wrapper for your auth logic. Something like this simple class with static functions:
<?php
class Auth
{
public static function login($identifiant, $password)
{
// query db then
// $_SESSION['Auth']['id'] = value from db
return self::id();
}
public static function isLogged()
{
return (bool)self::id()
}
public static function id()
{
return (isset($_SESSION['Auth']['id'])) ? $_SESSION['Auth']['id'] : false)
}
public static function logout()
{
$_SESSION['Auth'] = array();
}
}
// usage
Auth::login($_POST['identifiant'], $_POST['password']);
if (Auth::isLogged()) {
$sql = "select * from posts where user = " . Auth::id() . "";
}
Auth::logout();
If you are "pretty sure it is due to the fact that the id info in (your) table is an int, and the one from the session array isn't".
Then here's a simple way to convert your session id from array into a variable (cast it).
$id = (int)$_SESSION['id'];
Hope it helps.
you should not enclose integers in single quotes in the SQL
try this
$result = mysql_query("SELECT * FROM usr_users WHERE usr_id = $id AND usr_pass = '$pass'");

issue with my update-query

I'm trying to submit an update function, but for some reason it's not working and I can't figure out why... Someone who does?
UPDATE SQL-SYNTAX:
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
INSERT FUNCTION:
public function insert($sql) {
mysql_query($sql, $this->_connection);
return mysql_affected_rows($this->_connection);
}
PHP:
$project = new Project();
$project->name = $_POST['newproject_name'];
$project->photo1 = $_FILES['images']['name'][0];
if($project->updateProject($_DB, $projectname)) {
$feedback = "OK!";
} else {
$feedback = "NOT OK!!";
}
And in case you were wondering, $project->name and $project->photo1 are filled in correctly.
Any ideas? I hope I gave you everything you need, if not, let me know!
EDIT 1: I used the 2 first answers, but no results. Yet...
EDIT 2: I also don't get anything from $feedback
It looks like you have a stray opening parenthesis after the SET keyword. Remove it.
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
public function updateProject($db, $id)
requires 2 parameters being passed but when you do
if($project->updateProject($_DB))
you're only passing 1??
Your updateProject needs two variables and the second one is missing in your call, resulting in an invalid query.
Edit: Based on your edit; I'm guessing $id needs to be an integer or a string, you are passing an object.
Exactly what row do you want to update? I don't see anything in your php code that defines the ID of the row you want to modify, you are just generating a new object, not getting one from a database for example.

using functions to simplify CMS theming

I'm in the process of making my own CMS. I have some code that selects database rows to be echoed out on the page like so:
$query = mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error());
However whenever I try to put this inside a function and call the function instead of using that long lines of code, nothing happens. Am I missing something with PHP functions?
function posts() {
mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error()); `
}
while($row = mysql_fetch_array(posts())) {
$id = $row['id'];
echo $id;
}
You need to return the result:
function posts() {
return mysql_query("SELECT * FROM posts order by id desc") or die(mysql_error()); `
}
Without seeing your function code, it's impossible to say what the problem is, but if I had to guess based on your description, the first thing I'd check is to see if you are (a) returning $query in your function and (b) assigning the return value to something else in your calling code.
UPDATE: So, based on the code you posetd, yes, the problem is (a) above--you need to return the value. Just put "return" before the rest of the one line of code in the function and it should work.

Categories