I am using a foreach statement to extract data from a SQL table and am using an array to loop through every single piece of data I need. Previously I just set the variables for the extracted data equal to the array IDs. Now I would like to instead concatenate a string to the array ID names but am not sure how to accomplish this.
Basically I would just like to add "_type" to every single variable name such this it is no longer named $Banana but §Banana_type instead.
I have tried changing the $$val to $$val . '_type'. However this didn't work. I am quite sure I just need to concatenate the '_type' somehow and would appreciate if anyone can help me out.
$variablesArray = array(
"Apple",
"Banana",
);
foreach($variablesArray as $val) {
$query = "SELECT * FROM {$tableName} WHERE ID = '{$CI_NOYEARS}'";
$result = mysqli_query($conn, $query) or die('error');
while($data = mysqli_fetch_array($result)) {
$$val = $data["COINFO"];
}
}
If you really really need to have variable variables you can concatenate the variable name and store it in another variable like this:
$varName = 'foo'.'1';
$$varName = 1; // $foo1 = 1;
or you can concatenate without the variable in between:
$var = 'v';
echo ${$var.'ar'}; // echoes 'v'
But you can see how ridiculously unclear it gets. This is terrible design choice to use variable variables and it will also confuse your IDE intellisense, static analyzers, and so on. Please don't use variable variables. A better choice would be an array:
$myVars = [];
$myVars['foo'] = 'bar';
Related
I have an array returned from MYSQL query with 2 LEFT JOINs.
Question is: "Is there another way for writing the code below?". I got the code but I want a more clear way of it just to understand what happens inthere.
CODE:
$result = array();
while ($resultArr = mysqli_fetch_assoc($booksAndAuthors)) {
$result[$resultArr['book_id']] ['book_name'] = $resultArr['book_title'];
$result[$resultArr['book_id']] ['author'][] = $resultArr['author_name'];
print_r($result);
}
With the extract() function you can make the data in the result into variables. I have put the example below inside a function, so they will be local variables.
function getBooksAndAuthors($queryResult)
{
while ($data = mysqli_fetch_assoc($queryResult))
{
extract($data);
$BooksAndAuthors[$book_id] = array('book_name' => $book_title,
'author' => $author_name);
}
return $BooksAndAuthors;
}
This makes the code a lot more readable. You will, of course, have to know which columns there are in your database table. I also left out the extra '[]' for the author.
Here's how I recommend writing it, because I don't think you should depend on automatic creation of intermediate arrays.
$result = array();
while ($row = mysqli_fetch_assoc($booksAndAuthors) {
$bookid = $row['book_id'];
if (!isset($result[$bookid])) {
# First time we see this book, create a result for it
$result[$bookid] = array('book_name' => $row['book_title'],
'author' => array());
}
# add this author to the result entry for the book
$result[$bookid]['author'][] = $row['author_name'];
}
It's essentially equivalent, but I think it also makes the logic clearer.
I have a table called global_settings with 2 columns (field, value)
i need a way to make each row a variable
so for example:
is field = title and value = hello i would need:
$title = 'hello';
I have tried doing this:
$global_sql="SELECT * from global_settings ";
$global_rs=mysql_query($global_sql,$conn) or die(mysql_error());
while($global_result=mysql_fetch_array($global_rs))
{
$global_sql2="SELECT * from global_settings where field = '".$global_result["field"]."' ";
$global_rs2=mysql_query($global_sql2,$conn) or die(mysql_error());
$global_result2=mysql_fetch_array($global_rs2);
$global_result2["field"] = $global_result2["value"];
}
but that didn't work - any ideas?
I strongly suggest you do not auto-create variables from your DB. You'll be littering your script's namespace with potentially useless variables, and probably overwriting other variables you DID want to keep separate. Do it as you are - store the settings in an array.
Plus, unless I'm totally misreading your code, there's absolutely no reason for the sub-query. A simple:
$settings = array();
$sql = "SELECT field, value FROM settings"
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$settings[$row['field']] = $row['value'];
}
is all you need to grab all of the settings.
This line will not create a variable named after the value for field.
$global_result2["field"] = $global_result2["value"];
You can create an array variable, for example:
$array_of_results[ $global_result2["field"] ] = $global_result2["value"];
This way you will have the following array:
[ 'field' => 'value' ]
I'm trying to pull an array to use on another query but it's not working, because the last comma.
<?php
include"connection.php";
$pos = mysqli_query($not,"SELECT * FROM equipos");
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
$enjuego = mysqli_query($not,"SELECT * FROM partidos WHERE dprt='ftbls'");
while($part=mysqli_fetch_array($enjuego)){
$liga=$part['serie'];
$eq1= $part['eq1'];
$eq1s= strtoupper($eq1);
$eq2= $part['eq2'];
$eq2s= strtoupper($eq2);
echo $logos[$eq1].'<br>';
}
?>
It gives me the same error over and over again.
This is the closest I came but just doesn’t work.
Can someone tell me what am I doing wrong?
The error I get is: Warning: Illegal string offset 'gua' in line 22
You have several problems with your code:
You never created an array
You constantly overwrite $logos
Your usage of substr_replace() indicates a deeper problem.
Here's a better approach:
Build the array.
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
There are many ways condense an array into a string. I encourage you to browse the manual on PHP Array Functions. In your case, you are interested in implode()
$logos = implode(",", $logos);
Note: The value for $logos smells. You should construct your arrays to hold data, not formatting.
For example:
$logos[$row['abrv']] = $row['logo'];
Output:
print_r($logos);
What you want can be achieved in many ways, but let's look at your code, there are quite a few things wrong in there.
Semantically meaningless variable names like pos, not, equipos, abrv. Only logo and result are good variable names.
Using the * selector in database queries. Don't do that, instead select the exact fields you need, it's better for performance, maintainability, code readability, testability, ... need I say more?
Fetching per row and running code on each row when what you actually want is an array containing all rows. Solution:
$result = mysqli_query($not, "SELECT * FROM equipos");
$logos = mysqli_fetch_all($result, MYSQLI_ASSOC);
Concatenating subarrays by using strings, that's not how it works, what you could do:
while($row = mysqli_fetch_assoc($result))
{
$logos[][$row['abrv']] = $row['logo'];
}
But as I said, that's not necessary.
Overwriting your variable $logos with each iteration of the loop. You'd need to do $logos[] = ....
Typically, implode is useful for such cases.
Without knowing what exactly you want to do, take this as a first hint:
$logos = array();
while($row= mysqli_fetch_assoc($pos)){
$logos[] = "<br>'".$row['abrv']."'=>"."'".$row['logo']."'";
}
$logos = implode(",", $logos);
The simplest way I would have thought is just to change the query and fetch the array into that -
<?php
include_once("connection.php");
$result = mysqli_query($not,"SELECT abrv, logo FROM equipos");
$rows = mysqli_fetch_array($result, MYSQLI_ASSOC);
// display the result
echo "<pre>"
print_r($rows);
echo "</pre>"
?>
I would like to create 3 different arrays which can change depending on which fields are pulled from some mysql tables.
This is the code I have:
// Gather db rows with query
$compQuery['subCats'] = mysql_query("SELECT id,name,category FROM subcategories ORDER BY id DESC");
$compQuery['cats'] = mysql_query("SELECT id,name FROM categories ORDER BY id DESC");
$compQuery['mans'] = mysql_query("SELECT id,name,link FROM manufacturers ORDER BY id DESC");
// Place rows into arrays
foreach($compQuery as $name=>$query){
$name = array();
while($data = mysql_fetch_array($compQuery[$name])){
foreach($data as $key=>$value){
$$name[$key] = $value;
}
}
}
What I would expect this to produce is 3 arrays: subCats, cats and mans each with the value pairs. Instead of finding the $$name variable and assigning [$key] = $value to the array it is taking a single letter out of the $$name variable and assigning the $value to this new variable.
For example, if $name = 'subCats', $key = '3', and value = 'machine tools'
It would create the variable $C using the 3rd letter in subCats:
$C = 'machine tools'
What it should do is create:
$subCats[3] = 'machine tools';
Now, obviously there are easier ways to create separate arrays for each query, and I have modified my code to a lazier/easier version. However, I am still curious as to how I would go about assigning a key value pair to a double dollar sign variable.
Any help would be greatly appreciated! I have the simple code working now, but would like to implement this new code to be more dynamic and allow for more queries as needed without hassle.
Thanks!
Josh
${$name}[$key]
But I do not like to create 'unknown' variable, as in variables whose name is not in the code... What if the name is 'key','db','_GET','compQuery' etc? All hell breaks loose...
In this line:
$name = array();
You're overwriting $name. You probably meant to write to $$name:
$$name = array();
I tried to make the title of this most the most descriptive as possible, as I don't know how to do this... I know the best way will be value storage in some form of array.
My question is this, I have this query where I need to pic the tag name and the correspondent id for a later comparison and use ($tag_nome is collected by $_GET):
$resultado2 = mysql_query("SELECT tag.tag_nome, rel_frasetag.id_tag
FROM tag, rel_frasetag
WHERE rel_frasetag.id_tag = tag.id_tag AND
rel_frasetag.id_frase='$id_frase'") or die(mysql_error());
while($res2 = mysql_fetch_array($resultado2))
{
$tag_nome2 = utf8_encode($res2['tag_nome']);
$id_tag = $res2['id_tag'];
}
I already tried some things like array_push() but couldn't get it to work.
At the end of this snippet I'm comparing $tag_nome2 against $tag_nome to see if they match. If so, it will echo one link with the corresponding $tag_nome2 and $id_tag, and if not will echo pretty much the same thing, with a different class on the link.
My best guess as far as what you want to do is the following:
if( $tag_nome2 == $id_tag )
{
// do something
}
else
{
// no match
}
Perhaps though, you're saying your variable names are being overwritten? You're inside of a while loop, so the values they'll ultimately receive will be that of $res2[] at the end of the last iteration of your loop.
And if you're saying you want to save your rows for later, you can do:
$holder = array();
$res = mysql_query("");
while( $row = mysql_fetch_assoc($res) )
{
$holder[] = $row;
}
print_r($holder);