Accessing from another function an extracted row from an sql table - php

I have a php auxiliary function called extractFromID() in a file called auxiliary.php which queries a database for a specific line in a table which has a specific ID value and then extracts all the columns from that line.
function extractFromID() {
$connect = mysql_connect("localhost", "root","") or die ("erro a abrir a ligação.");
mysql_select_db ("hospitaldatabase");
$query = 'SELECT * FROM ' .$_SESSION['listtype']. ' WHERE (ID_' .$_SESSION['listtype']. '="'.$_SESSION['id'].'")';
$results = mysql_query($query) or die(mysql_error());
while($rows = mysql_fetch_array($results){
extract($rows);
}
}
From another file, I am trying to access the variables extracted by the function extractFromID() from $rows using
<?php
include('auxiliary.php');
extractFromID();
Although, I seem to be unable to access the extracted values, since I get undefined index errors. What am I doing wrong?

You need to understand variable scope. When you declare a variable inside a function, its scope is limited to that function. You can expand its scope by declaring it to be $GLOBAL but, in your case, the best solution is to return the values you want to use
function extractFromID() {
$connect = mysql_connect("localhost", "root","") or die ("erro a abrir a ligação.");
mysql_select_db ("hospitaldatabase");
$query = 'SELECT * FROM ' .$_SESSION['listtype']. ' WHERE (ID_' .$_SESSION['listtype']. '="'.$_SESSION['id'].'")';
$results = mysql_query($query) or die(mysql_error());
$data = array();
while($rows = mysql_fetch_assoc($results)){
$data[] = $rows;
}
return $data;
}
$myvars = extractFromId();
echo $myvars[0]['fieldname'];
As for undefined variables, it could be you've not called session_start() at the top of your pages before setting your $_SESSION variables. That would mean they are undefined.

Related

how do i create a php function to echo out mysql data, a function that can be reused?

I need to write a PHP function to echo out MySQL rows as I give it the SQL query I want to be executed as the function argument. I have tried out the following code but it is giving me an undefined index error
function runQuery($query) {
$conn = mysqli_connect('localhost', 'root', '', 'mydb');
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
the code I am using to call the function is;
runQuery(SELECT * FROM mytable WHERE id='5')
echo $resultset['name'];
this, however, gives me this error, undefined index 'resultset' on line 25. any kind assistance would be appreciated
You dont have a $resultset in the scope of where you call the function. The function creates one, but that is only visible inside the function.
You will also have to put QUOTES around the query, you are passing a string there so it needs to be quoted.
Your errors should have generated quite a few error messages, if you were not getting them I have added 4 lines of code you should add while testing code for example if you are testing on a LIVE server with error reporting turned off.
You should also change the function to ensure you always return something
So amend the call to
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
function runQuery($conn, $query) {
$resultset = [];
$result = mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
$resultset = runQuery($conn, "SELECT * FROM mytable WHERE id='5'");
// as result will now be a multidimentional array
// you will need to loop over that to get each returned row
foreach ( $resultset as $row ) {
echo $row['name'];
}
AFTER your edit there is another error
$conn is not created inside the function, so will be invisible in the function code unless passed as a parameter to the function (there is another way but lets not get into the bad habit of using global variables)
First, your code is probably vulnerable to SQL Injection. Please take care of that, by using prepared statements for instance.
https://www.w3schools.com/sql/sql_injection.asp
https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection
Other than that, you do not assign the return value of your function to a variable. You cannot use the $resultset defined in the function scope outside the function, as it is a different scope. Try the following:
$resultset = runQuery("SELECT * FROM mytable WHERE id='5'")
echo $resultset['name'];
I built a similar function recently - here is my code
function returnSQL($conn, $nameSql) {
$result = mysqli_query($conn, $nameSql);
if (!$result) {
return 0;
}
while ($res = mysqli_fetch_assoc($result)) {
$data[] = $res;
}
return $data;
}
The connection is setup outside the function and passed in as an argument along with the sql like this...
$conn = mysqli_connect($servername, $username, $password, $DBName);
if (!$conn) {
echo 'Failed to connect to database :- ' . $DBName . '<br>';
die();
}
$sql = "SELECT * FROM table";
$data = returnSQL($conn, $sql);
I'm no expert, but this works for me :)
What I notice from your code is that you are trying to access $resultset outside of the function it is declared in and I think it is not available as a global variable - perhaps it should be something like:
$returnValue = runQuery(SQL statement);
// $returnValue is assigned the array returned from runQuery()
echo $returnValue['name'];

PHP MySQL Query Where x = $variable from function

Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);

mysqli_connect in a function throws error

I'm sure the question is easy to answer, but I don't get it.
When I try to connect in a function it throws me an "Access denied for user''#'localhost'" error. It looks like the array isn't available in the array, because the error says I didn't enter a username and password.
The code is:
$config["mysql_host"] = "localhost";
$config["mysql_user"] = "myusername";
$config["mysql_pass"] = "mypass";
$config["db_name"] = "mydb_name";
$config["event_tname"] = "tablename";
function get_events(){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die ("Error, please contact the provider!"/* . mysqli_error()*/); //execute
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
events(); //just an example: call the function
What do I have to change at the array?
Regards,
Franz
At first you should consider using mysqli object-orientated. There is no reason to use procedural style anymore.
Secondly global PHP variables are not available inside of functions, therefore you need to pass the array to the function as explained in the other answer.
See this article for more information on PHPs variable scope.
Imho the best solution would be to use a class for your application and store the config as private attributes. Methods of that class will then have access to the attributes.
just add global $config; inside your function as
function get_events(){
global $config;
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events(); //ju
or pass the config param to function
function get_events($config){
$mysqli = mysqli_connect($config['mysql_host'], $config['mysql_user'], $config['mysql_pass'], $config["db_name"]); //connect to mysql and select the database
$sql = "SELECT * FROM ".$config["event_tname"]; //a simple query
$result = mysqli_query($mysqli, $sql) or die("Connection error: " . mysqli_connect_error());
while($all_events = mysqli_fetch_assoc($result)){ //fetch and just print it
foreach($all_events as $key => $val)
echo($val." | ");
}
mysqli_free_result($result);} //END -- clear $result
get_events($config); //ju

Fatal error: Call to undefined function availableDate()

I get this error when trying to run this, what do it mean?
if(isset($_POST['submit']))
{
$date = $_POST['date'];
$partySize = $_POST['partysize'];
$catering = $_POST['catering'];
print_r($date);
print_r($partySize);
print_r($catering);
include "/diska/www/include/coa123-13-connect.php";
$host='co-project.lboro.ac.uk';
$dbName='coa123wdb';
$dsn = "mysql://$username1:$password1#$host/$dbName"; //Data Source Name
require_once('MDB2.php'); //Just include this line into your program - you do not have to have the source in your directory
$db =& MDB2::connect($dsn); //Try to make a connection
if (PEAR::isError($db)) {
die($db->getMessage());
}
//step 1 - query
$sql = "SELECT * FROM venue
WHERE capacity >= $partySize";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
$valueIDArray = array();
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
$values = implode(',', $valueIDArray);
$query = "SELECT * FROM venue_booking
WHERE venue_id IN ($values)";
//step 2 - executing the query
$result1 =& $db->query($query);
if (PEAR::isError($query)) {
die($result1->getMessage());
}
while($row = $result1 -> fetchrow()){
$idValue[] = $row[0];
$dateValues[] = $row[1];
}
availableDate($dateValues,$date,$idValue, $db); //Line error points to
function availableDate($bookedDates, $date, $idValue, $db){
I have commeted on the line the error points to, this file works when its in its own PHP file but when inside the if(isset($_POST['submit'])) statement it does not work. What am I doing wrong?
Move the function definition outside the if statement. There's almost never a good reason to do that -- the only excuse might be if you wanted different definitions of the function depending on a condition, but that doesn't seem to be what you're doing. If you define a function inside an if, you have to define it before you call it; functions defined at top-level can be called from anywhere.
call availableDate after it's defined, if you already have to define it inside of if statement.
Ex.
function availableDate($bookedDates, $date, $idValue, $db){
...
}
//and then call it...
availableDate($dateValues,$date,$idValue, $db); //Line error points to
EDIT:
Example of non-working function defined inside of conditional statement
if(1){
func('a');
function func($a){
echo $a;
}
}
This wont work, but this will:
if(1){
function func($a){
echo $a;
}
func('a');
}

Unable to execute MYSQL query inside a PHP function

PHP:
function generate_uid() {
$uid = mt_rand();
$sql = "SELECT user_id
FROM user_registration";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability = TRUE;
while($row = mysql_fetch_array($result)) {
if($row['user_id'] == $uid) {
$availability = FALSE;
}
}
if($availability == FALSE) {
generate_uid();
}
}
The error
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in E:\Web Design EC\register2.php on line 8
Error:
But when i execute this function as normal php there is no error and the $uid is generated. What maybe the problem??
$con is not defined in the current variable scope. You can pass the connection to function as a parameter:
function generate_uid($con) {
...
mysql_query($sql, $con);
}
$uid = generate_uid($con);
Or you can use global:
function generate_uid() {
global $con;
...
mysql_query($sql, $con);
}
$uid = generate_uid();
Or, simply leave the connection variable out, and the last opened connection will be used:
function generate_uid() {
...
mysql_query($sql);
}
$uid = generate_uid();
All of those should work.
To learn more about variable scope, check out the PHP manual on the subject at:
http://www.php.net/manual/en/language.variables.scope.php
You are using $con in your function, but $con is not defined in your function scope.
http://php.net/manual/en/language.variables.scope.php
You need to either
a) Pass $con to your function or
b) Set $con as a global
c) Not use $con at all eg.
if (!mysql_query($sql))
however make sure that your app is only connecting to ONE database, otherwise you will run into issues because when you don't specify a connection it will use the last connection opened.
Inside your function, your MySQL connection doesn't exist. You either need to pass it in, or use the global keyword:
$con = mysql_connect('localhost', 'mysql_user', 'mysql_password');
function generate_uid()
{
global $con;
$uid = mt_rand();
$sql="SELECT user_id FROM user_registration";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query($sql);
$availability=TRUE;
while($row = mysql_fetch_array($result))
{
if($row['user_id']==$uid)
{
$availability=FALSE; }
} if($availability==FALSE) { generate_uid(); }
}
while($row = mysql_fetch_array($result))
You can't use that if you plan to use $row as an associative array. Use:
while($row = mysql_fetch_assoc($result))
instead.
EDIT
MYSQL_BOTH is turned on by default, forgot about that. The problem is pointed out by the other users, regarding the connection not being available in the function scope.

Categories