I am working on a PHP script that should get data from MySQL.
Here is what am I doing:
<?php
include('db.php');
session_start();
$doctor_actual=$_SESSION['doctor_actual'];
echo $doctor_actual;
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit,$adjacent);
}
function showData($data,$con,$limit,$adjacent){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "select * from tb_opiniones_doctor where codigo_verificacion = '".$doctor_actual."' order by id_opinion_doctor asc";
$rows = $con->query($sql);
$rows = $rows->num_rows;
$sql = "select * from tb_opiniones_doctor where codigo_verificacion = '".$doctor_actual."' order by id_opinion_doctor asc limit $start,$limit";
$data = $con->query($sql);
$str='<table><tr class="head"><td>Id</td><td>Firstname</td><td>Lastname</td></tr>';
if($data->num_rows>0){
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
$str.="<tr><td>".$row['id_opinion_doctor']."</td><td>".$row['id_opinion_doctor']."</td><td>".$row['id_opinion_doctor']."</td></tr>";
}
}else{
$str .= "<td colspan='5'>No Data Available</td>";
}
$str.='</table>';
echo $str;
pagination($limit,$adjacent,$rows,$page);
}
My problems are at the two queries, they only work if I put the real value for $doctor_actual, not as variable.
I have echoed the value for $doctor_actual, it is 9dv2ACvtwn2.
If I put in the queries ..where codigo_verificacion = "9dv2ACvtwn2"... the queries work fine.
If I put:
codigo_verificacion = '".$doctor_actual."'
or
codigo_verificacion = '.$doctor_actual.'
or
codigo_verificacion = $doctor_actual
it shows the message:
No Data Available
You should read about Variable scope. $doctor_actual outside function and $doctor_actual inside function are two different variables. As you can read above something like that
<?php
$var = 'text';
function myFunc()
{
global $var;
echo $var; // 'text'
}
will solve your problem.
But as noticed #Sean in comments below it's better idea to pass value as a parameter. Just add additional parameter to your function and pass value during function call.
Related
I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));
So I have my code
function GetApi($connection,$UserId){
global $Apicall;
$Apicall = array();
$Apiidquery = mysqli_query($connection, "SELECT ID FROM ` Characterapi` WHERE UserId = '$UserId'");
while($results = mysqli_fetch_assoc($Apiidquery)){
$Apicall[] = $results['ID'];
}
}
The output of this function if I call
$Apicall[0] = 3
$Apicall[1] = 11
and this is the information I want. But now I want to use a function like
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$Keyidquery = array();
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ID = '$Apicall'");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
This code does run if i set $Apicall ="3"; The issue im having is that I want the first function to get All the IDs associated with $userId in my data base then for each Id run the second function to to get the two specific pieces of information from that query.
In response to the comment below, this is the solution which I would use. However you should be wary of using this method as it does not parameterize the values, and as such not sanitized.
<?php
function Keyquery($Apicall,$connection ){
global $keyidcall, $keyid ,$Vcode;
$string = "ID IN('";
$string.= implode("','", $Apicall);
$string.="')";
$Keyidquery = mysqli_query($connection, "SELECT keyid, Vcode FROM `Characterapi` WHERE ".$string.";");
$results = mysqli_fetch_object($Keyidquery);
$keyid = $results->keyid;
$Vcode = $results->Vcode;
}
?>
I have a code that works when I use it on a page but Im trying to make this a function. I cant get it to work, it seems like the variables $customer and $system arent being sent through to the code. Even if I type it in Raw. Any idea whats wrong? $Customer is the name of the customer, $system can be 'Source' or 'Target'.
function status_total($customer, $system){
$sql_customer = "SELECT * FROM `Customer` WHERE Cust_Name = '$customer' LIMIT 0,1";
$customer_selection = mysqli_query($conn,$sql_customer);
$customer_row = mysqli_fetch_assoc($customer_selection);
$env_lines = $customer_row["Env_Lines"];
$cust_id = $customer_row["Cust_ID"];
$sql_last_records = "SELECT * FROM $system WHERE Cust_ID = $cust_id ORDER BY Time DESC LIMIT $env_lines";
$record_selection = mysqli_query($conn, $sql_last_records);
$result = mysqli_fetch_all($record_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else
echo "Fail";
}
https://gist.github.com/R2D2-05/78d81566e4bf0eafd1fa
The problem with your code is $conn variable which is treated a local variable inside a function. You should:
function status_total($customer, $system){
global $conn;
$sql_customer = "SELECT * FROM `Customer` WHERE Cust_Name = '$customer' LIMIT 0,1";
$customer_selection = mysqli_query($conn,$sql_customer);
$customer_row = mysqli_fetch_assoc($customer_selection);
$env_lines = $customer_row["Env_Lines"];
$cust_id = $customer_row["Cust_ID"];
$sql_last_records = "SELECT * FROM $system WHERE Cust_ID = $cust_id ORDER BY Time DESC LIMIT $env_lines";
$record_selection = mysqli_query($conn, $sql_last_records);
$result = mysqli_fetch_all($record_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else
echo "Fail";
}
Or you can also pass the $conn through the function, so change the function's definition to:
function status_total($conn, $customer, $system){...}
I am writing a script to access a specific detail about the user and I was hoping to make the database query be function.
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ID'";
$s = mysql_query($q);
$r = mysql_fetch_array($s);
}
But when I try and use it it will not access the row the way I want it to.
$user = '999';
connectUser($user)
echo $r['name'];
But if I put echo $r['name']; in the function it will work.
your function is not returning anything. add return $r['name'] at the end of function.
then echo connectUser($user);
thare are 2 major problems in your code
the function doesn't return anything and you don't assign it's result to a variable.
Your variables doesn't match. $ip doesn't seem the same variable with $ID
so, this one would work
function connectUser($id) {
$q = "SELECT * FROM users where ID=".intval($id);
$s = mysql_query($q);
return mysql_fetch_array($s);
}
$user = '999';
$r = connectUser($user)
echo $r['name'];
That's because the variable $r isn't being returned by the function, so it's never being set outside of the function. Here's what you should have:
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ip'";
$s = mysql_query($q);
return mysql_fetch_array($s);
}
And then outside have:
$user = '999';
$r = connectUser($user)
echo $r['name'];
You might also want to take a look at this question: prepared statements - are they necessary
This function is not working,
as you did not supplied the database connection into function,
and you did not return anything (PHP will return NULL)
Please understand what is variable scope first,
and the function
A workable example, can be like :-
function connectUser($db, $ip)
{
$q = "SELECT * FROM users where ID='$ID'"; // vulnerable for sql injection
$s = mysql_query($q, $db); // should have error checking
return mysql_fetch_array($s); // value to be returned
}
How to use :-
$db = mysql_connect(...);
$res = connectUser($db, "some value");
The first question is how to run a function using the URL, I have the following function:
function do_curl($start_index,$stop_index){
// Do query here to get all pages with ids between start index and stop index
$query = "SELECT * FROM xxx WHERE xxx >= $start_index and xxx <= $stop_index";
Now when I'm trying to do curl.php?start_index=0&stop_index=2 this is not working but when i delete the function and WHERE idnum = 1 it is working.
Now the second question is how 'compile' all the fields from the rows to arrays? I have the current code:
$query = "SELECT * FROM fanpages";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query = '\'http://graph.facebook.com/'.$row['page_id'].'\', ';
echo $fanpages_query;
}
$fanpages = array($fanpages_query);
$fanpages_count = count($fanpages);
echo $fanpages_count;
echo $fanpages_query; returning
'http://graph.facebook.com/AAAAAA', 'http://graph.facebook.com/BBBBBBB', 'http://graph.facebook.com/CCCCCCCC',
(I don't have an idea how to do it in a different way, also when im doing it in such a way i can't delete the final comma which will return PHP-error.)
echo $fanpages_count; returns 1 and like you can see i have 3 there.
Thanks in advance guys!
Do a function call to do the query
function do_curl($start_index, $stop_index){
...
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
For your second question, you can use arrays and the implode function to insert commas:
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
Then use implode to print them out:
echo implode(',', $fanpages);
The whole code:
function do_curl($start_index = 0, $stop_index = null) {
$queryIfThereIsNoStartIndex = '';
$queryIFThereIsNoStopIndex = '';
$queryIfBothStartAndStopIndexAreMissing = '';
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$fanpages_query[] = 'http://graph.facebook.com/'.$row['page_id'];
}
return $fanpages_query;
}
$fanpages = do_curl($_GET['start_index'], $_GET['stop_index']);
$fanpages_count = count($fanpages);
echo implode(',', $fanpages);
And you should totally use mysql_escape_string for escaping the values you add to the query.