Ok basically I can't figure out how to get the imploded result from mysql back to a usable variable in php. The array is throwing me for a loop, and driving me nuts.
The checkboxes that are being dynamically created from the db:
<input name="tournament_id[]" value="'.$row['tournament_id'].'" type="checkbox">'.$row['tournament_name'].'
The posted value getting imploded (no sql injection prevention implemented yet):
$got_tournament_id = implode(",",$_POST['tournament_id']);
This gets inserted into mysql like this:
id user_id tournament_id
1 16942627 1,10
This is my mysql query to grab the imploded data:
$query = ("SELECT tournament_id FROM tournament WHERE user_id=16942627");
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$got_it = $row['tournament_id'];
}
$bust_him = var_dump(explode(",", $got_it));
echo $bust_him;
The above using var_dump is returning the following:
array(2) { [0]=> string(1) "1" [1]=> string(2) "10" }
Now this is where I am totally lost, and can't figure out what to do to get the values 1 and 10 from the array into individual variables. I have tried several ways to do it and I keep ending up with errors, or just the word array. I need some help if anybody can give some. Thanks in advance.
Don't var_dump(), whose purpose is debugging, not code or display logic. Just store the output of explode() into $bust_him (what a weird variable name):
// Store the output of explode() directly
$bust_him = explode(",", $got_it);
// No need for individual variables, just access via array keys.
echo $bust_him[0];
echo $bust_him[1];
// etc...
If you have a fixed number of elements, you can use list() to place into variables:
// You know you only have two, so you can use list()
// to store directly into variables
list($first, $second) = explode(",", $got_it);
echo $first;
echo $second;
In the long run, a better solution than storing comma-separated values in your table is to create a separate, properly normalized table which links tournament_id to user_id. You then have multiple rows per user_id, each containing one tournament_id. This makes for much simpler and more efficient querying in a lot of instances, enabling the use of COUNT() aggregates for example, among many other benefits.
Related
I'm experiencing a strange issue while running a mysql query from php.
I have a mysql database with many (23) tables; two of them are Users and FollowersList.
FollowersList contains two colums: in the first one there's the code of a user, and in the second one the code of the user that the first one is following; each column references the primary index of Users table.
I have defined a stored procedure called "getFollowings" that returns the codes of the users that someone is following; it is defined in this way:
CREATE PROCEDURE getFollowings(IN cod INT(11))
BEGIN
SELECT Code2 FROM FollowersList WHERE Code1=cod;
END
When I call the stored procedure from phpmyadmin, everything works fine; I get all the correct results.
When I call it from php, using this code:
$sql0="CALL getFollowings('".$cod."')";
$res0=mysqli_query($con, $sql0);
$array0=mysqli_fetch_array($res0);
mysqli_next_result($con);
I can't get the correct results. The connection is defined correctly, and all the variables are correctly defined.
Let's make an example. I'm working on the user with code 94; when I run the procedure from phpmyadmin, I get two results: 63 and 89, which is correct in my database.
If I try the same from a php script, I get an array of dimension 2, but with only the first value; the var_dump is:
array(2) { [0]=> string(2) "63" ["Code2"]=> string(2) "63" }
This means that I receive and array with size=2, but with only one element stored. Do you have any idea why?
You are not iterating the mysqli_fetch_array.
Use like this
while($row = mysqli_fetch_array($res0)){
$array0[] = $row;
}
print_r($array0);
and you are using mysqli_fetch_array which give both associative array and numeric array.
If you want associative array use
mysqli_fetch_array($res0,MYSQLI_ASSOC);
If you want numeric array use
mysqli_fetch_array($res0,MYSQLI_NUM);
as default it return both
use like this
while($row = mysqli_fetch_array($res0)){
$array0[] = $row;
}
echo count($array0);
foreach($array0 as $value){
echo $value[0];
}
In mySQL I have a table with 8 rows, id and status.
$make=mysql_query("SELECT id, status FROM data order by id");
My question is how can I avoid using the foreach or any loop to echo the data, but instead to ave something like
<?php echo $row['status with the id 5']; ?>
and in another place of the page to echo the status with id 8 ?
You can utilize the following pattern:
$contents = [];
foreach($results as $result) {
$contents[$result->id] = $result;
}
$results contains the MySQL result set. $contents will be the associative array. It would be more comfortable if you swapped that to a function or class which works for all the tables you want to access applying this pattern. Depending on which database class you use, it might be necessary to cast the key to an integer, otherwise there will be problems accessing the index if it is passed as a string.
Note that you furthermore should migrate your code to MySQLi or PDO first.
If your table is likely to become very big, you should not implement this. Instead, it would be better if you checked in the first place which entries will be needed and load those explicitly with an IN() query.
i'm relatively new to coding and I need a little help. I'm basically trying to loop through an entry in a mySQL database and push any new entry into an array , so that it only comes up once in my array.
// SQL query
$response = $bdd->query('SELECT serie_bd FROM inventaire_bd');
//creating array to group all elements from the db so that they do not repeat
$serie_bd_groupe=array();
while($data_collected = $response->fetch())
{
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
{
array_push($data_collected,$serie_bd_groupe);
}
}
Will this work? - it seems like the loop will just stay stuck after it comes accross an entry a second time because the if statement wont execute itself.
Also in the future, are their any php equivalent to jsfiddle.net so i can test code syntaxically?
Thank you for your time
Your array keys will be default integers, so you don't want to check those. Instead of this:
if(array_key_exists($data_collected,$serie_bd_groupe)==false)
you should do this:
if(!(in_array($data_collected,$serie_bd_groupe)))
http://php.net/manual/en/function.in-array.php
On the other hand, if you're expecting your collected data to be the array key rather than value, you'd do something like this, instead of your array_push:
$serie_bd_groupe[$data_collected] = 1;
then your key check would work.
If you are looking for UNIQUE values (serie_bd) from your database, update your query to include "DISTINCT" like this:
$bdd->query('SELECT DISTINCT serie_bd FROM inventaire_bd');
On the other hand, I think you are looking for http://phpfiddle.org/
I am attempting to alphabetically organize an options list populated from an array; the problem is that the array array contains html tags at the front so sorting it seems imposable. I have tried 'ORDER BY' in the mysql query from which the array variables are pulled, but the command gets lost.
The whole system seems hardwired to sort the list by the key column in the mysql table, which is simply not acceptable. Is there any way around this issue? Any help would be VERY appreciated!
Here is an example of what I'm trying to do:
$options = array();
$query1=mysql_query("Select * From table1 Where name='blah'");
while($queryvalue1=mysql_fetch_array($query1)) {
$array1 = $queryvalue1['Column1'];
$query2=mysql_query("Select * From table2 Where id In ($array1) Order by value DESC");
while($queryvalue2=mysql_fetch_array($query2)) {
$var1 = $queryvalue2['Column2'];
$var2 = $queryvalue2['Column3'];
$options[] = "<option value='$var'>$var2</option>"
}
}
$options = implode(PHP_EOL, $options);
There's certainly ways to do it, but they are all much slower than letting the database sort for you.
It might not be the simplest solution, but I'd suggest getting rid of the HTML tags and repopulating the database, even if you have to use a temporary table while you fix the rest of your code. Do it right so you don't have to continually work around a serious problem for the rest of the application lifecycle.
I have a MySQL field which stores an array with 3 values:
array(item1=>1123, item2=>5454, item3=>23432)
How can I query the database with PHP so that I get only distinct values of item2 and then arrange those results by the values of item3?
A lot more information is needed - like, how your database is structured.
Look into the DISTINCT() function and the ORDER BY clause of SQL
It much easier to store your array into text and something you can separate later. Using php you can do this. I'll try to work with your data here into something you can use. says you have the field items. If instead you had an array such as.
$items = array(1123,5454,23432);
You can then implode it with a symbol such as:
$items = implode('|',$items);
and then store this in the database under a fields such as items that would look like this:
1123|5454|23432
Then when you want to grab the data you just need to explode it with the same symbol:
$items = explode('|',$row['items']);
and you are back with your dataset:
$items[0] = 1123
$items[1] = 5454
$items[2] = 23432
and then can access the second item by grabbing element one of the array:
$items[1]
Hopefully that gives you a better understanding of it.