Trying to define variables from the results of a query in php - php

I am trying to define variables from the results of a query, but I cannot manage to get this to work. I am trying to make my site multilangual, so I want to define a lot of text items (identifiers) that I have stored in a database. The table looks like this:
ID, Identifier, English, Dutch
1, Owned_by, "Owned by", "Eigendom van"
2, Owner_of, "Owner of", "Eigenaar van"
etc
etc
where the Column Identifier is the variable that I want to define and 1 of the 2 languages is the value that I want to give the variable. I have define a previous query from which the result is the language requested by the user, so $language_2 is the outcome from the previous query. So when $language_2 = "Dutch", I would like all the records in the table to be defined with the value in the column "Dutch".
When I use the code below the variables will be printed (echoed) but I cannot use them as an actual variable to use in my site.
$sql_3 = "SELECT Identifier, ".$language_2." as Language FROM translate";
$result_3 = mysql_query($sql_3) OR die (mysql_error());
while ($row_3 = mysql_fetch_array($result_3))
{
echo "$".$row_3['Identifier']." = '".$row_3['Language']."';<BR>";
}
How can I get them to actually become a variable that I can use in my site?

Add brackets arround the string that is the variable name:
${$row_3['Identifier']} = $row_3['Language'];

You can use mysql_fetch_assoc() to get an associated array if you must use the older mysql_* functions, then use variable variables to get what you want
$$row_3['Identifier'] = $row_3['Language'];

${$row_3['Identifier']} = $row_3['Language'];

Related

How to use wildcard in PHP query

I have a table filter feature in PHP club membership webpage. I made it so the user can filter the table and choose which members to display in a table. For example, he can choose the country or state where the member is from then hit display. I am using a prepared statement.
The problem is, I need to use wildcards to make the coding easier. How do I use a wildcard in PHP MySQL query? I will use wildcards for example if the user does NOT want specific country but instead he wants to display all members from all countries.
I know not specifying the WHERE country= will automatically select any countries but I already constructed it so each controls like the SELECT control for country already has a value like "CA" or "NY" and "*" if the user leaves that control under "All Countries". This value when submitted is then added to the query like:
$SelectedCountry = $_POST["country"];
sql .= " WHERE country=" . $SelectedCountry;
But the problem is using WHERE country=* doesn't seem to work. No errors, just doesn't work. Is "*" the wildcard in PHP MySQL?
The * is not a wildcard in SQL when comparing with the = operator. You can use the like operator and pass a % to allow for anything.
When doing this the % should be the only thing going to the bind. $Bind_country = "'%'"; is incorrect because the driver is already going to quote the value and escape the quotes. So your query would come out as:
WHERE country ='\'%\''
The = also needs to be a like. So you want
$bind_country = '%';
and then the query should be:
$sql = 'select * from table where country like ?';
If this were my application I would build the where part dynamically.
Using * in WHERE clause is not right. You can only give legit value. For example:
// looking for an exact value
SELECT * FROM table WHERE column = 'value'
// you can also do this when looking for an exact value
// it works even if your $_POST[] has no value
SELECT * FROM table WHERE column = 'value' OR '$_POST["country"]' = ''
// looking for a specific or not exact value
// you can place % anywhere in value's place
// % denotes the unknown characters of the value
// it works also even if your $_POST[] has no value
// results will not be the same when you're using AND or OR clause
SELECT * FROM table WHERE column LIKE '%val%'
I think below link can solve your problem.
Just have a look and choose what you need.
Thanks.
http://www.w3schools.com/sql/sql_wildcards.asp

Running a MySQL query using a string in php

Answer found (syntax): The column name of my string had to be encased in backticks " ` " as they contained spaces. Note that this means that the majority of this post has no relevance to the issue. The code has been corrected in case someone wants to do something similar.
So, I am doing a foreach loop to assign a value (1/0) to non-static columns in my database (it needs to support addition/deletion/editing of columns). I am using $connectionvar->query($queryvar); to do my queries which worked fine up until now when I'm trying to use a custom built string as $queryvar in order to change the column name to a variable within the loop. I've been outputting this string through echo and it looks exactly like my functional queries but somehow doesn't run. I've attempted to use eval() to solve this but to no avail (I feel safe using eval() as the user input is radio buttons).
Here's the loop as well as my thought processes behind the code. If something seems incoherent or just plain stupid, refer to my username.
foreach($rdb as $x) { //$rdb is a variable retrieved from $_POST earlier in the code.
$pieces = explode("qqqppp", $x); //Splits the string in two (column name and value) (this is a workaround to radio buttons only sending 1 value)
$qualname = $pieces[0]; //Column name from exploded string
$qualbool = $pieces[1]; //desired row value from exploded string
$sql = 'UPDATE users SET '; //building the query string
$sql .= '`$qualname`';
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\''; //$profilename is retrieved earlier to keep track of the profile I am editing.
eval("\$sql = \"$sql\";"); //This fills out the variables in the above string.
$conn->query($sql); //Runs the query (works)
echo ' '.$sql.' <br>'; //echoes the query strings on my page, they have the exact same output format as my regular queries have.
}
}}
Here's an example of what the echo of the string looks like:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
For comparison, echoing a similar (working) query variable outside of this loop (for static columns) looks like this:
UPDATE users SET profiletext='qqq' WHERE username='Admin2'
As you can see the string format is definitely as planned, yet somehow doesn't execute. What am I doing wrong?
PS. Yes I did research this to death before posting it, as I have hundreds of other issues since I started web developing a month ago. Somehow this one has left me stumped though, perhaps due to it being a god awful hack that nobody would even consider in the first place.
You need to use backticks when referring to column names which have spaces in them. So your first query from the loop is outputting as this:
UPDATE users SET Example Qualification 3='1' WHERE username='Admin2'
But it should be this:
UPDATE users SET `Example Qualification 3`='1' WHERE username='Admin2'
Change your PHP code to this:
$sql = 'UPDATE users SET `'; // I added an opening backtick around the column name
$sql .= '$qualname`'; // I added a closing backtick around the column name
$sql .= '=\'$qualbool\' WHERE username=\'$profilename\'';
Example Qualification 3 : Is that the name of your Mysql Column name ?
You shouldnt use spaces nor upper / lower case in your columnname.
Prefere : example_qualification_3
EDIT :
To get column name and Comment
SHOW FULL COLUMNS FROM users

Error in Comparing the same column in mysql

I am fetching the values from the column as the value of integer and doing this for two user so i tried to get the value from the table and compare it but unfortunately for both greater and smaller comparsion i am getting the same result nothing changed.
How do i compare the column values?
My code is like below-----
$sqlres="select membership from register where mid='".$_SESSION['mid']."' ";
$pres=mysql_query($sqlres);
$prest=mysql_fetch_array($pres);
$sqlres1="select membership from register where matri_id='".$row['mtr_id']."' ";
$pres1=mysql_query($sqlres);
$prest1=mysql_fetch_array($pres);
if($pres<$pres1)
{
//somethiung enter code here
}
First of all don't use mysql_* it is deprecated, use mysqli_* or PDO instead.
As for your question, mysql_fetch_array as the name suggests, returns an array, not a single value, so you need to get the first value in the array:
if($pres[0]<$pres1[0])
{
//somethiung enter code here
}
You save the result in $prest and $prest1 (with "t"), not in $pres and $pres1. I suggest always using the variable $query for the query string and $result for the result table. Only when you fetch the result should you use a custom variable name to not get confused.
You can use something like
if($prest['membership']<$prest1['membership']){//do stuff here}
In the piece of code that you provided, you are comparing the resources that mysql_query returned not the values of the columns. You have to do this:
if( $prest['membership'] < $prest1['membership'] ){
//Some stuff going here
}
Advice: Name your variables properly. Use more describing names. After 2 months you won't remember the difference between $prest and $prest1

User Defined $_get value goes wrong n mysql query for search

Hello, I am new in php may be this one may be pretty much easy for you, but I'm stuck here
I have a $_get value $varialbe which is being use in mysql query in where = '$variable'
if it doesn't match any where value, it returns error.
Tutorials abound on this subject and hundreds of questions exist about getting started with PHP and passing variables into MySQL queries, etc.
Are you sure you've been through a few of those?
Variables from an HTML form passed as part of the URL get put into a $_GET array by PHP. So if you have a textbox with a name of "age" and a user submits it with a value of "20" you will see this URL:
http://domain.com/page.php?age=20
This value will be accessible using $_GET['age'] in PHP. To pass this value to MySQL you then would incorporate the value into the query, but only after doing some basic security and sanitizing!
$age = mysql_real_escape_string($_GET['age']);
Your MySQL query can then use this value like so:
$query = "SELECT FROM table WHERE age = $age;";
$result = mysql_query($query) or die(mysql_error());
Post your code and actual error messages for more specific answers and assistance.

PHP: MySQL Query with fieldname in a var

Little question: With the following code...
<?php
$statement = "SELECT * FROM TABLE";
$query_unfetched = mysql_query($statement);
$query_num = mysql_num_rows($query_unfetched);
if ($query_num !== 1) {
exit;
}
$query_fetched = mysql_fetch_object($query_unfetched);
$fielname = "ID";
echo $query_fetched->$fiedname;
?>
With this code, there is no output, because PHP somehow does not check that in $fieldname is an existing name of a field in the selected Table.
Why doesn't it work, have I made a mistake? Or are there any other ways to select a field whose name is saved in a var?
Thanks for the help!
Instead of using mysql_fetch_object, you could use mysql_fetch_assoc. It will return the result as an array, after which you can simply use your variable as a key.
I'd suggest using var_dump on the $query_fetched. Some OS's and DB's will return different capitalizations. Oracle, for one, will always return the column names as capital. I've seen MySQL only return lower in one circumstance.
You can also use the fetch_assoc as suggested by Cpt. eMco and that will give you warnings if the array key is not set. (Remember to turn warnings off in production though).
(I do need to put in an obligatory plug for the PDO classes. I find them far more intuitive and clearer.)

Categories