I am struggling a little bit with a tricky PHP array. I am trying to retrieve data from a database (a single row) and I want to plug this data in a bunch of dynamically generated fields on the page (PHP).
My DB is organised as follows
____________________________
| cats | dogs | birds | cows |
_____________________________
| 30 | 40 | 22 | 34 |
______________________________
I would like to build an array like this:
array(
$cats => $cats_value
$dogs => $dogs_value
etc...
)
Importantly: I want the array to ouput variables, where in the above example $cats outputs "cats" and $cats_value outputs "30". I am guessing once this is done that I can use the variable names directly, so I won't have to go nuts trying to pull them out of the array...
I have tried to put various bits of code but have failed miserably (i.e. nothing to show/embarrass myself with on here.)
Any help would be much appreciated.
OK, the code that provides the answer is as follows:
$query = "SELECT * FROM animals";
$result = mysqli_query($dbc, $query);
$data_array = array();
$row = mysqli_fetch_assoc($result);
print_r($row);
foreach($row as $key=>$value){ echo $key; echo $value;
${$key}=$key;
${$key."_value"}=$value;
}
echo "<br><br><br>";
echo $Cats." = ".$Cats_value."<br>";
echo $Dogs." = ".$Dogs_value."<br>";
echo ${"Cows"}." = ".$Cows_value."<br>";
echo ${"Birds"}." = ".$Birds_value."<br>";
I appreciate all the answers that helped me find the answer to this. As an aside, the whole reason I am doing this is because I need to populate a dynamically generated PHP page with a bunch of variables, and that I will likely need to populate these variables dynamically as well.
If you think I am approaching this problem the wrong way, then please let me know (i.e. is it dumb to convert an associative array into a bunch of $variables? Does that make sense, and/or could it really slow down my page?)
Related
I want to get the value from the Epic[2] column.
The mysql table looks like that:
ID | Epic[0] | Epic[1] | Epic[2] | Epic[3]
-----------------------------------------------
440 xy xy xy xy
I have three variables where the informations are stored.
$qualitybudget = "Epic"
$budgetType = "2"
$itemlevel = "440"
I tried the following:
$sql = "SELECT '$qualitybudget'['$budgetType'] FROM `randproppoints` WHERE id = '$itemlevel'";
Output looks like that:
SELECT 'Epic'['2'] FROM `randproppoints` WHERE id = '440'
As you see 'Epic'['2'] has the wrong syntaxing. The output for the working query should be like: Epic[2]
What is the right syntax handling in a mysql query like that?
Use
$sql = "SELECT `${qualitybudget}[$budgetType]` FROM `randproppoints` WHERE id = '$itemlevel'";
instead. This way, the column name is exactly formatted as you wish and encapsulated.
Note that the syntax ${xyz} has to be used to make it clear that only xyz is the name of the variable and that this is all to be printed here. Otherwise, PHP assumes it is an array and evaluates the following squared brackets for the same string insertion. Another example where this syntax has to be used is if for instance you had a variable $a = "thing"; and wanted
$b = "there are three $as";
to get "there are three things". It would not work as PHP would assume you address a variable $as, but the fix would seem like this:
$b = "there are three ${a}s";
There's something weird going on.
I have I database which could look something like this:
table name: dm
|id|receiver|sender|msg |
|1 |John |Emma |Hey John! |
|2 |Emma |John |Hey! |
|3 |John |Emma |Whats up |
|4 |Emma |John |Not too much |
|5 |John |Keira |Have you got...|
I have an html page with a on it and for now what I want is for the messages that either
Emma sent to John => receiver = "John", sender = "Emma" or
John sent to Emma => receiver = "Emma", sender = "John"
to be displayed in the console.
I can do that with JQuery using the console.log() function.
My PHP looks like this:
$user1 = "John";
$user2 = "Emma";
$sql = "SELECT * FROM dm WHERE receiver = '$user1' AND sender = '$user2';SELECT * FROM dm WHERE receiver = '$user2' AND sender = '$user1'";
// Execute multi query
if (mysqli_multi_query($link,$sql))
{
do
{
$i = 0;
$msg = array();
if ($result=mysqli_store_result($link)) {
while ($row=mysqli_fetch_row($result))
{
printf("%s\n",$row[0]);
$msg[$i] = $row[0];
$i++;
}
mysqli_free_result($result);
}
}
while (mysqli_next_result($link));
}
echo json_encode($msg);
exit();
mysqli_close($link);
You will notice, that I have "printf" in there, because I wanted to see what the databse would give back to me. It correctly gave back the id's: 1,3,2,4.
However, I normally would like to do the request using JQuery ajax. I know how to do that also. Because of that I want to have an array which holds all the id's of the posts like this:
["1","2","3","4"]
Unfortunately the way I do it as written in the code what it returns to me is this:
["2","4"]
So what's going on is that he only puts what was in the first query into the array.
So what exactly is my question?
I want to fix the array to hold all the id's of the respective messages which would be 1,2,3,4. Preferably in this order as well and not like this 1,3,2,4.
I hope I made the problem clear and thank you for any advice!
You reset $i and $msg inside the outer loop. That means you will only see results from the second query in your array. Move the $i = 0; and $msg = array(); lines outside that loop.
That said, there’s no reason to do 2 queries here. Just use an OR in your WHERE clause to get both results at once. This will be faster and easier.
Also, this is very important: you are wide open to SQL injection. You need to use prepared statements, rather than concatenating variables into your query. See How can I prevent SQL injection in PHP?.
I have a question about how I can save different value in order if I GET 1 row in php.
For example, if I have like:
*Feder|100|50|10|5|9|0|0|0|0|0|0 PHP LINE
I need to save this row in the table like:
----------------------------------------------
name | score | status | point | level | bla | bla | bla....
----------------------------------------------
Feder| 100 | 50 | 10 | 5 | 0 | 0......
-------------------------------------------------
Now, I use easy method to get something in the database like:
$sql="INSERT INTO user (name, score, status)
VALUES
('$name','$score','$status')";
mysqli_query($con,$sql);
With this, when I get the value, I use like:
save.php?name=feder&score=100&status=50
But if I have to insert 40 values, will this be very hard? I think is possible to make easy, but I don't have any idea how I can do that... Someone know the best method to do this?
If I can use like: save.php?userdata=(all row)* is better...
What you ask for is not recommended for security reasons. It's one of the biggest no-nos to trust GET contents and put it straight into an SQL query.
But.
Of course you can foreach the variable $_GET like this:
$x="";
foreach($_GET as $key=>$val) {
$x.=" $key = '$val', ";
}
$sql = "insert into myTable set $x";
This is just the principle of it. You should ALWAYS check for the field names and values to avoid injection attacks. So a better approach would be like:
$isValid = array("name"=>1,"score"=>1,"status"=>1);
$x="";
foreach($_GET as $key=>$val) {
if(!$isValid[$key]) continue; // skip unknown fields!
$val = stripslashes($val); // remove magic quote junk
$val = mysql_real_escape_string($val); // protect mysql from attacks
$x.=" $key = '$val', "; // build the query
}
$sql = "insert into myTable set $x";
UPDATE
If you get all the values in one string like "aaa|bbb|ccc", you can use explode() to parse them into one array. But then you rely on the order of fields which is not a good practice. I'd recommend to always prefer "field1=aaa&field2=bbb" style.
Hope this helps.
Think about the risks and find your own way.
You said 40 row. You have to remember that the limitation of length of an URL. So the suitable way is to use POST method through a HTML form. Taking care in multible fields naming by adding [] to the field name:
<form method="post" action="some.php">
<input type="text" name="name[]" />
<input type="text" name="score[]" />
...
</form>
and from your PHP
for ($i = 0; $i < count($_POST['name']); $i++){
$name = $_POST['name'][$i];
$score = $_POST['score'][$i];
$status = $_POST['status'][$i];
$sql="INSERT INTO user (name, score, status)
VALUES
('$name','$score','$status')";
mysqli_query($con,$sql);
}
Notice: This answer is about the concept of inserting multiple records. It does not meant by the security of receiving data.
*MySQL will be upgraded later.
Preface: Authors can register in two languages and, for various additional reasons, that meant 2 databases. We realize that the setup appears odd in the use of multiple databases but it is more this abbreviated explanation that makes it seem so. So please ignore that oddity.
Situation:
My first query produces a recordset of authors who have cancelled their subscription. It finds them in the first database.
require_once('ConnString/FirstAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset1 = "SELECT auth_email FROM Authors WHERE Cancel = 'Cancel'";
$Recordset1 = mysql_query($query_Recordset1, $xxxxxx) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
In the second db where they are also listed, (table and column names are identical) I want to update them because they cancelled. To select their records for updating, I want to take the first recordset, put it into an array, swap out the connStrings, then search using that array.
These also work.
$results = array();
do {
results[] = $row_Recordset1;
} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1));
print_r($results);
gives me an array. Array ( [0] => Array ( [auth_email] => renault#autxxx.com ) [1] => Array ( [auth_email] => rinaldi#autxxx.com ) [2] => Array ( [auth_email] => hemingway#autxxx.com )) ...so I know it is finding the first set of data.
Here's the problem: The query of the second database looks for the author by auth_email if it is 'IN' the $results array, but it is not finding the authors in the 2nd database as I expected. Please note the different connString
require_once('ConnString/SecondAuth.php');
mysql_select_db($xxxxx, $xxxxxx);
$query_Recordset2 = "SELECT auth_email FROM Authors WHERE auth_email IN('$results')";
$Recordset2 = mysql_query($query_Recordset2, $xxxxxx) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
The var_dump is 0 but I know that there are two records in there that should be found.
I've tried various combinations of IN like {$results}, but when I got to "'$results'", it was time to ask for help. I've checked all the available posts and none resolve my problem though I am now more familiar with the wild goose population.
I thought that since I swapped out the connection string, maybe $result was made null so I re-set it to the original connString and it still didn't find auth_email in $results in the same database where it certainly should have done.
Further, I've swapped out connStrings before with positive results, so... hmmm...
My goal, when working, is to echo the Recordset2 into a form with a do/while loop that will permit me to update their record in the 2nd db. Since the var_dump is 0, obviously this below isn't giving me a list of authors in the second table whose email addresses appear in the $results array, but I include it as example of what I want use to start the form in the page.
do {
$row_Recordset2['auth_email_addr '];
} while($row_Recordset2 = mysql_fetch_assoc($Recordset2));
As always, any pointer you can give are appreciated and correct answers are Accepted.
If you have a db user that has access to both databases and tables, just use a cross database query to do the update
UPDATE
mydb.Authors,
mydb2.Authors
SET
mydb.Authors.somefield = 'somevalue'
WHERE
mydb.Authors.auth_email = mydb2.Authors.auth_email AND
mydb2.Authors.Cancel= 'Cancel'
The IN clause excepts variables formated like this IN(var1,var2,var3)
You should use function to create a string, containing variables from this array.
//the simplest way to go
$string = '';
foreach($results as $r){
foreach($r as $r){
$string .= $r.",";
}
}
$string = substr($string,0,-1); //remove the ',' from the end of string
Its not tested, and obviously not the best way to go, but to show you the idea of your problem and how to handle it is this code quite relevant.
Now use $string instead of $results in query
What is the best way to get the all values of one multiple select box, and then i want to save those values in one row in the database, then from that row i want to get each value separate. What is the best way to do such a thing ? My goal is to save the values and then get each separate.
You could do it this way
<select name="foo[]" multiple="multiple">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="fish">Fish</option>
</select>
<?php
$pets = $_POST['foo'];
//sanitize and verify the input here. Escape properly and what not
$query = mysql_query("INSERT INTO `pets` (`pet1`, `pet2`, `pet3`) VALUES ('".$pets[0]."', '".$pets[1]."', '".$pets[2]."')");
?>
But to be honest it's an awful way to go about building a database. It'll be very annoying or difficult to do anything meaningful with.
Why not have the following database setup:
users:
id | name
----------
1 | Tim
pets:
id | user_id | type
-------------------
1 | 1 | Fish
2 | 1 | Cat
3 | 4 | Kakapo
And then you would have a much more easily searchable and manipulatable database that's consistent.
I believe you should receive the value selected as an array in the $_POST variable so say your select has a name="products"
The values selected will be in $_POST["products"] assuming you are submitting the form via POST.
Then you can use the implode function to generate a string. For example:
$myProducts = implode("|", $_POST["products"]); //This will give you a pipeline delimeted string like : computer|laptop|monitor
$myProducts = mysql_real_escape_string($myProducts); //Just to santize before inserting in DB
Then just insert that string into the DB.
When retrieving the data you can reverse the process by using the explode function:
$myProducts = explode("|" , [The value retrieved from the database]); //This will give you an array which you can iterate and thus accessing the values individually.
Hope this helps :)
if i understand your question well...
$dataFromMultipleBox = array('data1', 'data2', 'data3');
$data = implode("||", $dataFromMultipleBox);
/*
After that,
write $data into database
fetch from the database again
*/
$pieces = explode("||", $rowFromDatabase);
foreach($pieces as $value) {
echo $value;
echo '<br>';
}
What is the best way to get the all values of one multiple select box,
Since it is PHP. Give the select element a name ending in [], then you can access them as $_POST['foo'][]
and then i want to save those values in one row in the database, then from that row i want to get each value separate.
Don't do that. Have a second table with two columns. The id (as a foreign key) of the row in the other table (where you were planning to store the data) and the value itself.