PHP SQL Function - php

Can someone please tell me why my function is not working?
function myappsbdo($sqlquery, $tabname)
{
try
{
$pdo = new PDO("mysql:host=127.0.0.1;port=3306;dbname=myapps","root","");
}
catch (PDOException $e)
{
echo "Problème de connexion";
exit();
}
$sql = $sqlquery;
$result = $pdo->query($sql);
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
I do a var_dump of the variable I chose for my $tabname and it's an empty array. There is suppose to have my db data in it...
Thanks!
EDIT: this is how I call it.
myappsbdo("SELECT * FROM categorie", $tab1);

The function argument $tabname was passed by value, therefore your subsequent assignment to that variable changes only the value of the function-scoped variable $tabname and not of the calling-scoped variable $tab1.
You want to pass by reference instead:
function myappsbdo($sqlquery, &$tabname) {
// ^---- notice the ampersand character
// etc.
$tabname = $result->fetchALL(PDO::FETCH_NUM);
}
Or, alternatively, return the resultset:
function myappsbdo($sqlquery) {
// etc.
return $result->fetchALL(PDO::FETCH_NUM);
}
$tab1 = myappsbdp('SELECT * FROM categorie');
Note that you probably ought to make your PDO object static, so that the database connection can be reused in successive function calls.

Related

PHP variables in function argument is not working

I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError

Unable To Access PHP Global Variable

I am trying to pull global variable $nsfw but it shows nothing at all. If I echo it inside function, it works. But outside, it fails even when defined as global. Kindly help me out here.
<?php
if(!function_exists('do_example_work'))
{
function do_example_work()
{
global $nsfw;
include("includes/dbconnect.php");
// Create connection
$conn = new mysqli($DBHOST, $DBUSER, $DBPASS, $DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT fieldname FROM table WHERE name='$anything'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["fieldname"] == 1) {
// do somethin
$nsfw = 25;
exit();
} else {
echo "enjoy";
}
}
} else {
echo "0 results";
}
}
echo $nsfw;
};
?>
There are arguments for and against Globals. You can search Stack and the internet and read about:
Globals are bad in many ways, and should be avoided where possible
Globals are not bad, and can be fine/safe to use if you know what you are
doing
The manual:
http://php.net/manual/en/functions.user-defined.php
You seem to be over complicating things with this basic user defined function.
OUT
If you want to get data out of a function, just use the return statement
function do_example_work() {
// Do some stuff here
$nsfw = 25;
return $nsfw; // Return where needed, in conditional statement or end of function
}
// Will echo "25"
echo do_example_work();
IN
FYI:
To get data into the function from outside, just pass the data into your function from the outside as an argument:
function do_example_work($nsfw) {
/** The var "$nsfw" will have whatever data you pass in through the function call
* You can use it as required - check if $nsfw == something
* Or it might be database login details (urgh)
*/
echo $nsfw." - And words from in the function";
}
// Will echo "Pass in argument - And words from in the function"
do_example_work("Pass in argument");
The keyword global in front of a variable name means that the variable is defined somewhere outside the function, and now I want to use that variable. It does not generate a global variable. So you need to define the variable outside the function, and then you can use that variable inside a function using the global keyword in front of it.
In your code I cannot see you defining the variable outside the function. You are just echoing it out at the bottom of your code.
Any specific reason for keeping global variable inside method ?? Move it outside method and it should work for u.
Or
Try GLOBALS as shown below.
function doit() { $GLOBALS['val'] = 'bar'; } doit(); echo $val;
Gives the output as :
bar
Or
<?php
foo();
bar();
function foo() { global $jabberwocky; $jabberwocky="test data<br>"; bar(); } function bar() { global $jabberwocky; echo $jabberwocky; } ?>

use a PHP variable from an included file

hi I avec a php file (inc.db.php) which contains my config to connect to my db.
Into this file I have something like
$dbh = new PDO(DSN, USER, PASS);
In a other file I included inc.db.php and in one function I want to use the $dbh variable.
My function is :
function getPassword($utilisateur) {
$uid = addslashes( $utilisateur );
$sql = "SELECT password FROM cc_users WHERE uid='$uid'";
$sth = $dbh->query($sql);
$result = $sth->fetchAll();
if (count($result) == 1) {
return TRUE;
} else {
return FALSE;
}
}
I got an error
PHP Notice: Undefined variable: dbh in /....
How I can do to use the variale included in a external file?
From the PHP Manual:
Any variable used inside a function is by default limited to the local
function scope.
(...)
In PHP global variables must be declared global inside a function if
they are going to be used in that function.
(...)
A second way to access variables from the global scope is to use the
special PHP-defined $GLOBALS array.
You'll avoid the error changing the function to this:
function getPassword($utilisateur) {
global $dbh;
$uid = addslashes( $utilisateur );
$sql = "SELECT password FROM cc_users WHERE uid='$uid'";
$sth = $dbh->query($sql);
$result = $sth->fetchAll();
if (count($result) == 1) {
return TRUE;
} else {
return FALSE;
}
}
But the usage of global variables is considered a bad practice.
Also, using addslashes won't protect your query against SQL injection attacks.
Prepare the SQL statements or use the quote method.

Unable to return PDO query result: Undefined Variable

I am having trouble outputting results from the following PDO query. When I try to process the resultant array I am left with an "Notice: Undefined variable: assets in..." error message.
I've tried numerous incarnations of the function and output but cannot get it to work correctly. Am I missing something here?
THE QUERY
function getAssets() {
global $dbc;
$query = "SELECT * FROM assets ORDER BY company ASC";
try {
$statement = $dbc->prepare($query);
$statement->execute();
$assets = $statement->fetchAll();
$statement->closeCursor();
return $assets;
} catch (PDOException $e) {
$error_message = $e->getMessage();
display_db_error($error_message);
}
}
THE VIEW
//call function
getAssets();
//display the results
foreach($assets as $asset) {
echo '<tr><td><b>Region:</b></td><td>'.$asset['company'].'</td></tr>';
}
I've tested the array and when I use
print_r($assets);
It will print the entire array, but looping would be useful. I've also tried fetching the data as an object to no avail.
Thank you! ... and thanks for not waxing poetic about global variables :)
$assets is a local variable in the function. To use it outside the function, you have to return it (which you do) and assign that result to a variable in the scope of the loop:
//call function and use it's result.
$assets = getAssets();

Retrieving list of items using php

I am trying to retrieve a list of items from a mySQL db and insert them as a list in a select object on a webpage. The following is the bit of code that isnt working.
In the first line, I am trying to retrieve a JSON object from a public function called getBrands() in a singleton object I have created called DatabaseInterface.
The second line is then attempting to turn that JSON object into a php array.
Finally, I am running a loop which can option each item in between tags for the webpage.
Where am I going wrong?
<?php
var $brandArrayJSON = DatabaseInterface::getBrands();
$brandArray = JSON_decode($brandArrayJSON);
for ($loop=0; $loop < sizeof($brandArray); $loop++) {
echo "<option>$brandArray[$loop]</option>";
}
?>
EDIT: In case it helps, here is my DatabaseInterface singleton. I have included this file at the top of my php file
class databaseInterface {
private static $_instance;
// Private constructor prevents instantiation
private function __construct() {
}
public static function getInstance() {
if (!self::$_instance) {
self::$_instance = mysqli_connect(self::databaseHost, self::databaseUsername, self::databasePassword, self::databaseName);
if (mysqli_connect_errno(self::$_instance)) {
throw new Exception("Failed to connect to MySQL:" . mysqli_connect_error());
}
}
return self::$_instance;
}
public function getBrands() {
try {
$con = DatabaseInterface::getInstance();
} catch (Exception $e) {
// Handle exception
echo $e->getMessage();
}
$query = "SELECT psBrandName from brands";
$result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con));
$resultArray[] = array();
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
$resultArray[] = $psBrandName;
}
return json_Encode($resultArray);
}
There is nothing "wrong" with the code, in that it should work (provided nothing is broken on the query-side). However, there are several things that should be improved.
First, basically what the getBrands() method is doing is equivalent to this:
$brandArray = json_encode(array('test','test2','test3'));
echo $brandArray; // returns ["test","test2","test3"]
Now, when you decode that you get the same thing you originally put in (an array):
$brandArray = json_decode('["test","test2","test3"]');
var_dump($brandArray); // Will dump an array
Since this is an array (not a PHP object), you can just use a foreach.
foreach($brandArray as $option) {
echo '<option>', $option, '</option>';
}
If you're worried about it being an object in some instances (maybe you had a non-array JS object which would be mostly the equivalent to a PHP associative array), you could cast the json_decode result into an array.
$brandArray = (array)$brandArray;
Now, in your getBrands() method, I would highly recommend just using $row['psBrandName'] instead of cluttering things up with extract, unless you have a really good reason to do this.

Categories