I have a script that displays countries in different languages. For example "United Kingdom" in Spanish would be "Reino Unido", etc. Every language is stored in a different table, like "name_es" for Spanish or "name_en" for English. The correct table is then selected through a session value stored for each user. What I have is this:
if ($countries_id)
{
$sql_select_countries = $this->query_silent("SELECT name_".$_SESSION['language']." as name FROM " . DB_PREFIX . "countries WHERE
id IN (" . $countries_id . ")");
if ($sql_select_countries)
{
while ($country_details = $this->fetch_array($sql_select_countries))
{
$countries_array[] = $country_details['name'];
}
}
}
Note that the problem line is this:
$countries_array[] = $country_details['name'];
I need it to be something like
$countries_array[] = $country_details['name_$_SESSION['language']'];
But I can't figure out the correct syntax :(
So you want to concatenate the string 'name_' with the vale stored in session?
$countries_array[] = $country_details['name_'.$_SESSION['language']];
I think if you add some speech marks and curly brackets you can do this:
$countries_array[] = $country_details["name_{$_SESSION['language']}"];
$countries_array[] = $country_details[$_SESSION["language"]];
Related
This one should be easy and it's killing me I can't find the solution!
I have a SQL query return records from a database. The two fields I am using are $row["staff_id"] and $row["name"].
From that I want to build a dynamic variable which is something like:
$staffid_1 = "Mark Smith";
$staffid_2 = "Sally Baker";
$staffid_3 = "Peter Pan";
The varibale name is created dynamically be combining "staffid_" and $row["staff_id"] for the first part then $row["name"] for the name.
I've tried:
${$staff_id . $row["staff_id"]} = $row["name"];
echo ${$staff_id . $row["staff_id"]} . "<br>";
But no luck! Any assistance would be appreciated :)
I would think you might be best to change your query to return the first part of it, then whatever you're calling it from to concatenate it together, eg
Query:
SELECT '$staffid_' + ltrim(rtrim(cast(staff_id as varchar))) + ' = "' + name + '"'
FROM [table list]
ORDER BY ...
Then concatenate the individual rows of result set as required, with in-between as you seem to require.
Okay so in PHP you have an awesome option to use a double leveled variable which basically means this :
$$varname = $value;
This results in the fact that if you have a string variable ,
(for example $staffid = "staffid_1") that you can do the following:
$staffid = "Jasonbourne";
$$staffid = "Matt Damon";
// Will result in
$JasonBourne = "Matt Damon";
So for your example:
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
Will result in the variable : $staff_id_1 = "Mark Smith";
To read more about double - leveled variables :
http://php.net/manual/en/language.variables.variable.php
EDIT: If you wanna loop through the rows :
foreach ($sql_result as $row) {
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
}
I'm creating a small project with PHP/MYSQL but i can't get my query working the way i need it. I have 2 tables
Table 1 (char):
Id, name.
Table 2 (spells):
Id, char, spell_name.
I'm getting the output:
Name Spell1
Name Spell2
Name Spell3
But I need it to be:
Name Spell1
Spell2
Spell3
Here's my query:
$query = "SELECT char.name AS name, spells.spell_name AS spell
FROM char, spells
WHERE (char.id = spells.spell_name)";
Any ideas?
I think you're gonna have to first get the ID of the character to query, and then pull the spells s/he has access to. Example:
$char_id = 0; // value would be assigned arbitrarily.
$query = "SELECT *
FROM 'spells' s
WHERE s.char = $char_id;";
$result = $pdo->query($query);
while($row = $result->fetchObj()){
// do something with the spells obj here
}
With SQL, you need to grab full rows at a time, so I believe the situation you want isn't possible.
As Goldentoa11 wrote. Make two selects, or create query with two result sets (more selects in one command), or accept current state (is normal and you can verify data consistency). I prefer current state, but sometimes use any of described solution (based on query frequency, size of result etc.).
If you need to list such data, you can than use something like this:
$currentName = null;
while ($row = mysql_fetch_object($result))
{
if ($currentName != $row->name)
{
echo "<b>" . $row->name . "</b><br />";
$currentName = $row->name;
}
echo $row->spell_name . "<br />";
}
I have a members site where users are given up to 7 web page templates to display their products on. Each template has the same field names, differentiated by _1, _2... _7 at the end of each.
For example:
// Template 1 would have the following list of variables
product_name_1
product_descript_1
product_color_1
product_price_1
// Template 2 would have the following list of variables
product_name_2
product_descript_2
product_color_2
product_price_2
// through Template 7
I am able to display any variables for a specific user within a web page, by use of a query string identifying their user_id in the url, ie
http://domain.com/folder/page.php?id=78
I then $_Get any variable by simply identifying it in the PHP file, ie
$product_name_1
$product_descript_1
$product_color_1
$product_price_1
My problem is that the url must identify WHICH template, since each template identifies a specific product, ie _1, _2, ..._7. How do I use a parameter in the url, such as
http://domain.com/folder/page.php?id=78¶meter=_7
...to identify all variables ending with _7, which would appear in the web page? The parameter used in the url would identify the variables to be used in the web page, whether _1, _2, etc.
UPDATE
I have tried the various answers with only partial success, ie "Array_x" is displayed when using any particular variable along with the suggested code. There may be a conflict with the rest of the code I'm using in page.php, as follows:
$db_connection = new mysqli("", "", "");
if ($db_connection->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
$prop_address=array(
"_1"=>"prop_address_1",
"_2"=>"prop_address_2",
"_3"=>"prop_address_3"
//Through to Temp 7
);
$prop_address{$_GET['parameter']}=$row->prop_address;
echo " $prop_address{$_GET['parameter']} ";
"Array_x" displays (where x=1, 2, 3, etc is used as the parameter in url, ie http://domain.com/page.php?id=72¶meter=1), instead of the actual value held in the database table for $product_name{$_GET['parameter']}. For some reason, the code is not picking up the value of the variable from the database table.
Would it be possible to use arrays so...
$product_name=array(
"1"=>"Product name for template 1",
"2"=>"Product name for template 2"
//Through to Temp 7
);
echo $product_name[$_GET["parameter"]];
You could then do the same for the other variables.
You could fill each array by doing something like:
$row = mysql_fetch_object($query);
$product_name[$_GET['parameter']]=$row->product_name;
echo $product_name[$_GET['parameter']];
I may be missing something...
$_GET['parameter'] = '_2';
$product_name{$_GET['parameter']} = 'string';
echo $product_name_2; // string
or
$_GET['parameter'] = '_2';
$var = 'product_name'.$_GET['parameter'];
$$var = 'string';
echo $product_name_2; // string
Personally, I would use array's for this type of behavior.
Update:
Although the above works and tested ok, it is a lot more work than anyone would probably desired.
In lieu of simplicity, I would suggest the approach via array's.
$templates = array(2 => array(
'product_name' => "value",
'product_descript' => "value",
'product_color' => "value",
'product_price' => "value",
);
foreach($templates[substr($_GET['parameter'],1)] as $var => $val){
$variable = $var.$_GET['parameter'];
$$variable = $val;
}
The above is backwards compatible, it uses substr to remove the leading _ from your parameter.
I couldn't get any of the answers given to work. I found an example given by a user for php variable variables in the PHP manual here and found it to work. I incorporated it into my code as follows:
$id = $_GET['id'];
$query = mysql_query("SELECT * FROM table_name WHERE id = '$id' LIMIT 1") or die(mysql_error());
$row = mysql_fetch_object($query);
for( $i = 1; $i < 8; $i++ )
{
$product_name[$_GET['parameter']] = "product_name_" . $i;
$product_descript[$_GET['parameter']] = "product_descript_" . $i;
$product_color[$_GET['parameter']] = "product_color_" . $i;
$product_price[$_GET['parameter']] = "product_price_" . $i;
}
${$product_name[1]} = "$row->product_name_1";
${$product_name[2]} = "$row->product_name_2";
${$product_name[3]} = "$row->product_name_3";
${$product_name[4]} = "$row->product_name_4";
${$product_name[5]} = "$row->product_name_5";
${$product_name[6]} = "$row->product_name_6";
${$product_name[7]} = "$row->product_name_7";
// List 7 variables and values for each field name
echo "${$prop_name[$_GET['par']]}";
The only problem is that mysql injection is possible with this code. If anyone could suggest a solution, I would greatly appreciate it.
I'm trying to code an array that displays a certain set of products depending on the gender of the logged in user. The arrays not really the problem but the parts where I'm going to have to check the database then create the conditional statement from the results is the main problem i think.
Here is my code:
<?php
include"config.php" or die "cannot connect to server";
$gender=$_POST['gender'];
$qry ="SELECT * FROM server WHERE gender ='$gender'";
$result = mysql_query($qry);
$productdetails;
$productdetails1["Product1"] = "£8";
$productdetails1["Product2"] = "£6";
$productdetails1["Product3"] = "£5";
$productdetails1["Product4"] = "£6";
$productdetails1["Product5"] = "£4";
$productdetails2["Product6"] = "£8";
$productdetails2["Product7"] = "£6";
$productdetails2["Product8"] = "£5";
$productdetails2["Product9"] = "£6";
$productdetails2["Product10"] = "£4";
if (mysql_num_rows($result) = 1) {
foreach( $productdetails1 as $key => $value){
echo "Product: $key, Price: $value <br />";
}
}
else {
foreach( $productdetails2 as $key => $value) {
echo "Product: $key, Price: $value <br />";
}
}
?>
You if statement is wrong. = is an assignment operator, you should use a comparison operator like == or ===
What happens with the current code?
Some tips:
First try echoing $gender, to make sure it is getting through. It is submitted through post, what happens if nothing is being posted? Where is this coming from? You should try to use get instead. This seems like something you'd give someone a link to therefore post doesn't make sense here. You could always have both, and just get post if it exists otherwise use get otherwise default to 'male' or 'female' depending on your audience.
Next, what is your query outputting? It might be empty at this point if gender is not giving anything back. It seems like you are querying for all rows where gender = whatever was passed, but then your if statement is asking was there anything returned? Then all you are doing is going to the arrays, but you shouldn't be doing that you should be outputting what you got from the DB. Assuming you do actually have products in the table called server you should do something like this:
$products = mysql_query("SELECT * FROM server WHERE gender ='$gender");
while($product = mysql_fetch_array($products)){
echo $product['name'] . " " . $product['price']. " " . $product['gender'];
echo "<br />";
}
On that note. You should really call your table something else, like product not just "server" unless by server you mean a table filled with instances of waiters or computer hardware.
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:
<div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>
There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:
regid | psc_1 | psc_2 | psc_3 | ...
My code:
if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = #each ($boxes)) {
$camp_string .= "'$camp',";
}
}
// The above to create a comma separated string
$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma
$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");
The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.
I'm not sure what I'm missing.
--
Update#1 (in reference to a comment below)
if(!empty($_POST['camps'])) {
$box=$_POST['camps'];
while (list ($key,$val) = #each ($box)) {
$camp_totals += $campcost[$val];
echo "$campdesc[$val] - $$campcost[$val]";
}
}
Why not name the checkboxes something different like the names of the columns, so that your $_POST comes back as:
// print_r($_POST);
array(
'regID' => 1,
'camp_filmore' => 1,
'camp_greenwald' => 1
'camp_idunno' => 1
);
From there it's fairly simple to build your query:
$query = "INSERT INTO registered (".implode(array_keys($_POST), ", ") . ") ".
"VALUES (" . implode(array_values($_POST), ", ").")";
You should obviously check to make sure the values of $_POST are properly escaped and sanitized before inserting.
A nice trick to remove the trailing comma would be.
$camp_string = rtrim($camp_string,',');
Anyway your query is not formated correctly.
INSERT INTO camps_registered (regid,'psc_1', 'psc_2', 'psc_3') VALUES ($regid,psc_1', 'psc_2', 'psc_3')
You cannot have single quotes in the first bracket
I think you should be looking at implode and you can easily add addition strings to it...
so e.g.
$comma_seperated = implode(',', $boxes);
$subscribed = $regid . ',' . $comma_seperated;