Reusing/overwriting the same variable name for mysqli_query? - php

I am using $sqlCommand variable name to validate my user access
$sqlCommand = mysqli_query($conn, "SELECT......
then I have another $sqlCommandProductList variable to check for my existing product list.
$sqlCommandProductList = mysqli_query($conn, "SELECT......
and I also have $sqlCommandMostPopular and $sqlCommandLatestProducts....
My question is is it possible to reuse the same variable name $sqlCommand throughout the page instead of creating so many variable name for sql query that only used once?

Of course, you can keep using it like this:
$sqlCommand = mysqli_query($conn, "SELECT name......");
...
// after the using is finished, just unset($sqlCommand)
unset($sqlCommand);
// define $sqlCommand again
$sqlCommand = mysqli_query($conn, "SELECT password......");
But do recommend another Strategy, it can be like this:
extract the ''database access process''(db process) into a independent method
return the info needed from the db process result
give the info a understanable name
like following:
function getName($conn, $sql) {
$sqlCommand = mysqli_query($conn, "SELECT name......");
...
// this is really needed
$name = ...;
return $name;
}
$name = getName($conn, $sql);

Sure is this possible.
As long you are sure you do not loose or overwrite data you still need for furhter processing.

Related

How to using LIKE operator which data saved in variable?

I need to search data in the database table.
I save data in a variable, then I want to display the data using it LIKE an operator when the data is called.
This is my code :
$data_input_user = $inFilter;
$data_input_user = mysql_real_escape_string($inFilter);
$sqlGetFreq = "SELECT * FROM termfrequency WHERE keyword LIKE
CONCAT("%",$inFilter,"%") ";
$freqResult = mysql_query($sqlGetFreq) or die(mysql_error());
Beside that i was trying this sql query
$sqlGetFreq = "SELECT keyword, frequency FROM termfrequency WHERE keyword LIKE '%$inFilter%' ";
$freqResult = mysql_query($sqlGetFreq) or die(mysql_error());
I was trying that code, but it failed.
Any idea please?
Thanks.
Try this
$sqlGetFreq = "SELECT keyword, frequency FROM termfrequency WHERE keyword LIKE '%".$inFilter."%' ";
Also please set the following to track any possible error.
ini_set("display_errors", "1");
error_reporting(E_ALL);

How to link variable and strings in PHP

I have a table called cms_settings. I name all the tabels with a prefix cms_ so i created a variable $dbpraefix="cms_"
when i call the entry using "select value from $dbpraefix.settings" command, it failed to proceed.
i also tried defferent version. like "select from '.$dbpraefix.'settings etc. nothing works.
but if i use "select value from cms_settings instead, it works!. how can i fix this. thanks a lot
<?PHP
function getSetting($property){
global $connection;
$dbpraefix= "cms_";
$sql= "SELECT value FROM $dbpraefix.settings WHERE property='$property'";
$ergebnis= mysqli_query($connection, $sql);
$row = mysqli_fetch_row($ergebnis);
return $row[0];
}
?>
Your query fails because in the string "...$dbapraefix.settings..." PHP doesn't realize that you want the . in the middle to be the string concatenation operator instead of a simple dot. As a result the string becomes cms_.settings instead of cms_settings
Change:
"SELECT value FROM $dbpraefix.settings WHERE property='$property'";
To
"SELECT value FROM {$dbpraefix}settings WHERE property='$property'";
You have a dot between the prefix and table name, that's why it won't work.
Try this: " . $dbpraefix . "settings.
The easiest way is to add a new parameter to your function so that when pass into the function it specify the table's name
Eg : $table = "settings";
function getSetting($property,$table){
global $connection;
$table= "cms_".$table;
$sql= "SELECT value FROM $table WHERE property='$property'";
$ergebnis= mysqli_query($connection, $sql);
$row = mysqli_fetch_row($ergebnis);
return $row[0];
}
change your query as below
$sql= "SELECT value FROM ".$dbpraefix."settings WHERE property='$property'";

PHP/mysql fetch multiple variables in array

I am new to PHP. I wanted to create a new record in another table but just one new variable gets returned. I've tried following:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_name = mysql_query("SELECT user_name FROM accept WHERE user_id=".$user_id." ");
$row1 = mysql_fetch_array($user_name);
$server = mysql_query("SELECT server FROM accept WHERE user_id=".$user_id." ");
$row2 = mysql_fetch_array($server);
$url = mysql_query("SELECT link FROM accept WHERE user_id=".$user_id."");
$row3 = mysql_fetch_array($url);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
And my result is this.
First of all, combine your queries into one:
$user_id = mysql_real_escape_string($_POST['user_id']);
$user_info = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row = mysql_fetch_array($user_info);
$lpoints = mysql_real_escape_string($_POST['lpoints']);
In order to create a new record, you will need INSERT INTO, to change existing records use UPDATE.
When you're fetching info from the database, it will be an array so you will need to use it accordingly. So essentially, to use the variables it will be like this:
$row['user_name'] or $row['server'] etc..
Also, look into using mysqli instead. You will need to change your connection script and some other syntax but it needs to be done. mysql is deprecated, insecure, and future support is not there so you will need to change it later anyway.
You should use pdo or mysqli and here is your code;
$user_id = &$_POST["user_id"];
if($user_id){
$result = mysql_query("select user_name,server,link,lpoints from accept where user_id='".mysql_real_escape_string($user_id)."'");
/*You should use single quotes for escaping sql injection*/
if($result){
$vars = mysql_fetch_array($result);
if($vars){
list($username,$server,$link,$lpoints) = $vars;
}
else{
//do something with errors
}
mysql_free_result($result);
}
else{
//do something with errors
}
}
else{
//do something with errors
}
Try This-
$user_id = mysql_real_escape_string($_POST['user_id']);
$result = mysql_query("SELECT user_name, server, link FROM accept WHERE user_id=".$user_id." ");
$row=mysql_fetch_array($result)
$row1=$row['user_name'];
$row2=$row['server'];
$row3=$row['link'];
$lpoints = mysql_real_escape_string($_POST['lpoints']);
Now you got what you wanted based on your requirement use the data to insert or update.

PHP DELETE immediately after select

I have a PHP server script that SELECTs some data from a MySQL database.
As soon as I have the result from mysql_query and mysql_fetch_assoc stored in my own local variables, I want to delete the row I just selected.
The problem with this approach is that it seems that PHP has done pass-by-reference to my local variables instead of pass-by-value, and my local variables become undefined after the delete command.
Is there anyway to get around this? Here is my code:
$query="SELECT id, peerID, name FROM names WHERE peer = $userID AND docID = '$docID' AND seqNo = $nid";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:1 getUsersNamesUpdate() query: ".$query."\n");
if (mysql_num_rows($result) == 0)
return array();
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query);
if (!$result)
self::logError("FAIL:2 getUsersNamesUpdate() query: ".$query."\n");
return $result;
You are overwriting your $result variable with your second statement:
$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query); // result does not contain the array anymore
Change the name to something else. It has nothing to do with call-by-reference or such.
Actually, your first assignment of the values is unnecessary as $row is already an array:
$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];
You could just do:
$row = mysql_fetch_assoc($result);
// at the end
return $row;
Then you don't even have to change your variable name for the second statement. But consider to use meaningful variable names.
First of all, why not just use only one query to delete the row that interests you ?
Something like this should do the trick, I suppose :
delete
from names
where peer = $userID
AND docID = '$docID'
AND seqNo = $nid
Of course, don't forget to escape/convert the values that should be ;-)
This way, no need for a select query, followed by a delete one.
Second : to make your code more easier to read / understand / maintain, you should probably not re-use the same variable for several different purposes.
Here, your $result variable is used for more than one thing, and it makes things harder to understand :
resource returned by the first mysql_query
then, array containing data from the first row
then, resource returned by the second mysql_query
It's a bit confusing, and will, one day or another, lead to errors...
Actually, it already has ;-) : the third assignment is overriding the data you're getting with the second ones, and boom, you've lost the information that corresponds to the row you've just deleted ;-)

PHP get result string from PostgreSQL Query

I'm new to PHP and SQL, but I need a way to store the result of an SQL Query into a variable.
The query is like this:
$q = "SELECT type FROM users WHERE username='foo user'";
$result = pg_query($q);
The query will only return one string; the user's account type, and I just need to store that in a variable so I can check to see if the user has permission to view a page.
I know I could probably just do this query:
"SELECT * FROM users WHERE username='foo user' and type='admin'";
if(pg_num_rows($result) == 1) {
//...
}
But it seems like a bad practice to me.
Either way, it would be good to know how to store it as a variable for future reference.
You can pass the result to pg_fetch_assoc() and then store the value, or did you want to get the value without the extra step?
$result = pg_query($q);
$row = pg_fetch_assoc($result);
$account_type = $row['type'];
Is that what you are looking for?
Use pg_fetch_result:
$result = pg_query($q);
$account_type = pg_fetch_result($result, 0, 0);
But on the other hand it's always good idea to check if you got any results so I'll keep the pg_num_rows check.

Categories