echo $uid; // RETURNS INTEGER VALUE
if (isset ( $_POST ['cashpaid'] )) {
$queryfinal = "select * from " . $db_prefix . "customer_det
where `id` = '$uid'"; // UID RETURNS NULL
....
I've tried everything and every combination of globals and super globals that I could think of. There's just no way I can transfer the value over.
I pull $uid from a MySQL select and it assigns to an integer value. As you can see at the start of the code, that ending curly brace is the end of an IF statement which contains the value for $uid.
How can I assign the same value to $uid across all scopes?
This has been killing me for about two days. I'm sorry if this seems elementary but it's about to drive me nuts. I tried $GLOBALS['uid'] to no avail.
You could try with a setter/getter function declared once in the global scope, but it doesn't do much more than accessing GLOBALS anyway.
function globalUid($value = False)
{
GLOBAL $__uid;
if (!isset($__uid))
$__uid = False;
if (False === $value)
return $__uid;
$__uid = $value;
}
Then instead of echoing $uid, try globalUid($uid) and, later, $saved_uid = globalUid();.
But I think it's possible the two scopes are executing across two different calls, so you might need to save the UID in the session variables.
Related
so I want to make a notification with AJAX call, that checks the sum of rows in database, then compare it the amount from before.
when the AJAX access the php file, first it will check if $old_db is already defined or not, if not then define it.
then it will run the query(not using prepared statement yet because this still experimental to me) to check, num_row query and the store the value into $new_db.
after that it will compare the value and goes on.....
then finally it will assign $new_db value to $old_db
if(!(isset($old_db)) && empty($old_db)){
$old_db = "";
}
$sql = $con->query("SELECT * FROM produk");
$new_db = $sql->num_rows;
if($new_db > $old_db){
echo "ada";
echo "<br>".$old_db;
}
$old_db= $new_db;
now the problem whenever I run the php file, it never echoed the value of $old_db even though I already assign a value to it at the bottom of the script
I guess everytime I run the script the value got assigned as "" or null again? so how do I prevent that and keep the last value?
I'm thinking about storing it into Cookie....
after thinking about it if I only want to use it as notification then using Session is enough. thank you guys
session_start();
$_SESSION['old_db'] = $old_db;
if(!(isset($_SESSION['old_db']) && empty($_SESSION['old_db'])){
$_SESSION['old_db'] = "";
}
$sql = $con->query("SELECT * FROM produk");
$new_db = $sql->num_rows;
if($new_db > $_SESSION['old_db']){
echo "ada";
echo "<br>".$_SESSION['old_db'];
}
$_SESSION['old_db']= $new_db;
So I am making a function where it takes in $name and $query as parameters to auto generate the 3 variables I need for a MySQL query.
Here is the code:
function makeQuery($name, $query){
}
And the variables:
$checkTeach = "SELECT * FROM users_table WHERE user_id LIKE '%2309%'";
$CTquery = mysqli_query($dbconn, $checkWho);
$CTrow = mysqli_fetch_assoc($CWquery);
Before I go onto my question I want to keep checkTeach in the name parameter and where it says CT it should be replaced with checkTeach.
So in a way I want it to look like this:
function makeQuery($name, $query){
$valueof($name)variable = $query;
$(valueof$name variable)query = mysqli_query($dbconn, $valueof($name)variable);
$(valueof$name variable)row = mysqli_fetch_assoc($(valueof$name variable)query);
}
One last question:
Should I manually declare these 3 variables above or should I use a function? Right now I have tons of those sets of 3 variables and I feel it would be easier with a function
Look into using variable variables. However, in your example, you need to consider if variable variables are the correct solution over an array, for example.
So let me explain my problem, lets assume that I run query like so:
$myquery = sql_query("SELECT name FROM table WHERE name='example' LIMIT 0,1");
Now.. I want to store the retrieved name into a variable so I would do something like this:
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
print"Name: $row_name";
}
$stored_name = $row_name;
NOTE: transfer_row() is just a function I wrote that takes $myrow['name'] and stores it in $row_name, for easier reference
Now, all is fine at this stage, here is where it gets interesting. Note that at this stage I still have a name assigned to $row_name. Further down the page I run another query to retrieve some other information from the table, and one of the things I need to retrieve is a list of names again, so I would simply run this query:
$myquery = sql_query("SELECT name, year FROM table WHERE DESC LIMIT 0,10");
while ($myrow = sql_fetch_assoc($myquery)) {
transfer_row($myrow);
$year = $row_year;
$link = "/$year";
print "<li style=\"margin-bottom: 6px;\">$row_name\n";
}
Now, I want to write an if statement that executes something if the $row_name from this query matches the $row_name from the old query, this is why we stored the first $row_name inside the variable.
if ($row_name == $stored_name){
// execute code
}
However as most of you know, this WONT work, the reason is, it simply takes $stored_name again and puts the new $row_name into $stored_name, so therefore the value of the first $row_name is lost, now it is crucial for my application that I access the first $row_name and compare it AFTER the second query has been run, what can I do here people? if nothing can be done what is an alternative to achieving something like this.
Thanks.
EDIT, MY transfer_row() function:
function transfer_row($myrow) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["row_$key"] = $value;
}
}
}
Without you posting the code for the function transfer_row, we won't be able to give you an answer that exactly matches what you request, but I can give you an answer that will solve the problem at hand.
When matching to check if the names are the same, you can modify the if statement to the following.
if ($row_name == $myrow['name']){
// execute code
}
What I suggest you do though, but since I don't have the code to the transfer_row function, is to pass a second variable to that function. The second variable will be a prefix for the variable name, so you can have unique values stored and saved.
Refrain from using the transfor_row function in the second call so your comparison becomes:
if ($myrow['name'] == $row_name)
If you need to use this function, you could do an assignment before the second database call:
$stored_name = $row_name;
...
transfer_row($myrow);
In your first query you are selecting the name field WHERE name='example' , Why are you quering then? You already have what you want.
Your are querying like:
Hey? roll no 21 what is your roll no?
So perform the second query only and use the if condition as :
if ($row_name == 'example'){
// execute code
}
Does it make sense?
Update
//How about using prefix while storing the values in `$GLOBAL` ??
transfer_row($myrow, 'old_'); //for the first query
transfer_row($myrow, 'new_'); //for the second query
function transfer_row($myrow, $prefix) {
global $GLOBALS;
if(is_array($myrow)) {
foreach ($myrow as $key=>$value) {
$key=str_replace(":","",$key);
$GLOBALS["$prefix"."row_$key"] = $value;
}
}
}
//Now compare as
if ($new_row_name == $old_row_name){
// execute code
}
//You'll not need `$stored_name = $row_name;` any more
include("connect.php");
$username = mysql_real_escape_string($_REQUEST[username]);
function updateData($key){
$field = "$$key";
if($field == "") {
} else {
$sql= "UPDATE users SET $key = '$field' WHERE username ='$username'";
mysql_query ( $sql , $conexion );
}
}
updateData('password');
updateData('firstname');
What I'm trying to make is an automatic way for this PHP file to recognize the fields and not save them if the input field value is empty.
If I mannually put the name of the field on the $key spaces, it works, but once I turn it into a function an run it, it doesn't work.
Don't write your code like this.
For starters, it's not readable - it makes whoever is maintaining the code have to go find this function to figure out where the data being used is coming from.
Secondly, you'll run into issues with variable scope - inside the function, none of your variables are defined unless you reference them with the global keyword to bring them into scope.
Instead, write your function like this:
function updateData($username, $key, $value){
if($key != "" && $value != "") {
$sql = "UPDATE users SET $key = '$value' WHERE username ='$username'";
mysql_query($sql, $conexion);
}
}
and pass in the relevant values; that's what function arguments are designed for. You might also want to consider escaping the contents of the arguments before interpolating them.
i think the problem , its that variables $username , $sql , $conexion not recognize in this function
look on this link variables scope
I'm trying to create a more succinct way to make hundreds of db calls. Instead of writing the whole query out every time I wanted to output a single field, I tried to port the code into a class that did all the query work. This is the class I have so far:
class Listing {
/* Connect to the database */
private $mysql;
function __construct() {
$this->mysql = new mysqli(DB_LOC, DB_USER, DB_PASS, DB) or die('Could not connect');
}
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$info = $result->fetch_object() or die('Could not create object');
return $info;
}
}
This makes it easy to access any info I want from a single row.
$listing = new Listing;
echo $listing->getListingInfo('','Books')->title;
This outputs the title of the first listing in the category "Books". But if I want to output the price of that listing, I have to make another call to getListingInfo(). This makes another query on the db and again returns only the first row.
This is much more succinct than writing the entire query each time, but I feel like I may be calling the db too often. Is there a better way to output the data from my class and still be succinct in accessing it (maybe outputting all the rows to an array and returning the array)? If yes, How?
Do you actually have a performance issue?
If your current setup works and doesn't suffer from performance issues, I wouldn't touch it.
This sort of DB access abstraction will likely become a maintenance issue and probably won't help performance.
Also, you're susceptible to SQL injection.
You should be able to store the whole object from the query into a variable and then access the single values from that object:
$object = $listing->getListingInfo('','Books');
$title = $object->title;
$price= $object->price;
But you can also use fetch_assoc() and return the whole assiciative array:
$array = $listing->getListingInfo('','Books');
$title = $object['title'];
$price= $object['price'];
This will give you the same results and also with only one query to the DB.
EDIT: If the getListingInfo() is the only function you should think of the following:
rename the function to prepareListingInfo() and within the function only prepare the query and store it in a class variable.
add a getNextListingInfo() function, which will return an object or associative array with the next row.
Using this new function, you can get every row that matches your query.
Either cache the result in an internal var
Or Comment it with a warning and explain to function users to copy the result in an var instead of calling it again and again with the same params
Yes, that would be calling the db too often.
A couple of solutions
1) put the listing info in a variable
2) cache the results in a hashmap or dictionary (be careful for memory leaks)