I have an app that records months and years by one CSV entry, i.e. db column named answer1 is jan,2008 and column answer2 is feb,2013. I want to use a specific month (jan) in html but it only gives me the last array data.
<?php
foreach ($row as $colName => $colValue )
{
if($colName === answer1 || $colName === answer2)
{
//break apart date data
$myArray = explode(',', $colValue);
echo '<div id=" ' .$colName . $myArray[0] . ' ">test</div> ';//this works
};
};
?>
I'd like something like this in another php block later in the doc.
<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>
This is probably a lot easier. We're exploding (or pulling two substrings) from the original columns in MySQL before we get to PHP. Then you can use them however you would like:
$query = "SELECT SUBSTRING_INDEX(answer1,',',1) as a1_month,
SUBSTRING_INDEX(answer1,',',-1) as a1_year,
SUBSTRING_INDEX(answer2,',',1) as a2_month,
SUBSTRING_INDEX(answer2,',',-1) as a2_year from my_table";
$result = mysqli_query($query);
$answers = array();
$x = 0;
while ($row = mysqli_fetch_array($result)){
$answers[$x]['answer1_year'] = $row['a1_year'];
$answers[$x]['answer1_month'] = $row['a1_month'];
$answers[$x]['answer2_year'] = $row['a2_year'];
$answers[$x]['answer2_month'] = $row['a2_month'];
$x++;
}
print_r($answers);
If for some reason you still want the concatenated strings you can do this:
$answer1 = $answers[0]['answer1_month'].','.$answers[0]['answer1_year'];
$answer2 = $answers[0]['answer2_month'].','.$answers[0]['answer2_year'];
Related
This question already has answers here:
MySQL Results as comma separated list
(4 answers)
Comma separated string of selected values in MySQL
(10 answers)
Just need a comma separated list from PHP/MySQL query [duplicate]
(5 answers)
Closed 2 years ago.
My goal: insert into a variable an array of items coming from a query and then print it
steps:
launch the query
do something with php
print the variable $report = 'this is your list: $list';
tried this:
$myquery = mysqli_query($dbconnection, "SELECT ...");
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, "; /* here I've the full list*/
}
$report = 'this is your list:' .$my_array. '.';
echo "$report"; /*I've only one item and not all the list*/
Your first echo is called several times because it is in the loop.
In every iteration you are replacing your content of $my_array.
Instead, try to attach it:
$my_array[] = $row['field'];
For more information see https://www.php.net/manual/de/language.types.array.php
This is normal.
Your while loop doing a "step" for each row found with your query.
You assigned $my_array as the "column" with the name field.
So at the end of the while loop, you'll get only the last column field of the last row.
Instead, try this
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
$myWholeList .= '$my_array '; // HERE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE
I've done a string concatenation, but you can do it with array and print_r() function. Have a look on this thread to see how to append data to an array.
mysqli_fetch_array while loop columns
EDIT:
Based on #isabella 's comment, she wants to display 7 items of array.
Two way :
Use print_r() or var_dump() which is the best to display an array (without taking care about rendering)
Add to $myWholeList variable each item.
e.g.
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
// HERE
foreach($row as $field) {
$myWholeList .= $field . ' ';
}
$myWholeList .= '<br>'; // NEW LINE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE
How do i str_split each character result output from mysqli database i have tried:
require("init.php");
$result = mysqli_query($conn, "SELECT item_name , quantity FROM books WHERE book = 1905515");
if($row = mysqli_fetch_assoc($result))
{
$da = $row["item_name"];
$qty = $row["quantity"];
}
$sql = mysqli_query($conn, "SELECT name , recharge , details , logo , price FROM promo WHERE code='$da' LIMIT 1");
if($rrow = mysqli_fetch_assoc($sql))
{
$code = $rrow["recharge"];
$see = str_split($code, 2);
echo "<br/>$see"; // not working fine, outputs 'Array'
echo "$code"; // working fine
}
all i get as result is 'arrary' thanks for your time and impact
A few directions here, I will give a few examples.
1) If you are simply wanting to echo out each row column, with a break, then all you need is this:
if($rrow = mysqli_fetch_assoc($sql))
{
echo '<br>' . $rrow['recharge'];
}
2) If you do need to split the 'recharge' column into 2-character array values, and then output those again as a solid string, you could do this:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
echo '<br>' . implode('',$codebits);
}
3) And if you needed to put each 2-character split on its own html row, you can add that to the implode like this:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
echo implode('<br>',$codebits);
}
4) However, how or what you are wanting to do with the code from 'recharge', is flexible at this point. Various ways we can go with it, and since its in an array, you can even wrap each array element in more html as you need:
if($rrow = mysqli_fetch_assoc($sql))
{
$codebits = str_split($rrow['recharge'],2);
foreach($codebits as $codebit) {
echo '<div class="something">'. $codebit .'<span>more html</span></div>';
}
}
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
while ($row = mysqli_fetch_array($r))
{
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2))
{
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID']=$row2['SpecID'];
$i++;
}
usort($ModDates); // <<< ??
$DeleteIDs[] = $ModDates[0]['SpecID'];
foreach ($ModDates as $ModDate)
{
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
?>
Hi I'm trying to Delete specifications from the product database (or at least get a list of ones to delete) where we have duplicates and we want to delete the oldest one.
So here I've 1) found a list of duplicate codes 2) Assigned spec id to each mod date 3) Sorted the mod dates to find the oldest*NOTE 4) Found a list of ids to delete by finding the id assigned to the first of the sorted array. 5) unsets the moddate array for the next set of duplicates
NOTE: I think solving this problem might have something to do with sorting the multidimensional array - this is the part that I'm fairly sure is wrong. If this wasn't a multidimensional array we would at least see the modification dates in order. At this point I COULD just do a search for product code and oldest (first in array) mod date which thinking about it now - would achieve the same result? Does it matter that the primary key will be lost - after all - all I need is to get rid of the product code with the older modification date.. it doesn't matter that we don't have the primary key?
P.S. I did see a post about sorting multi-dimensional arrays Here but I felt I should show you what I was doing in case somebody had a better suggestion?
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
That $a variable seems useless.
while ($row = mysqli_fetch_array($r)) {
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2)) {
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID'] = $row2['SpecID'];
$i++;
If $ModDates[] === $ModDates[$i], as you say, then write $ModDates[$i] in both assignments. $ModDates[] === $ModDates[$i]can be wrong, $ModDates[$i] === $ModDates[$i] cannot.
Moreover :
$ModDates[] = ...
$ModDates[$i]['SpecID'] = $row2['SpecID'];
Now, whatever has been assigned to $ModDates[$i] in the first line is gone, it's now an array with only one key : 'SpecId'.
}
usort($ModDates); // <<< ??
What does that comment mean ?
$DeleteIDs[] = $ModDates[0]['SpecID'];
You put only one value from the array into $DeleteIDs. Why ?
foreach ($ModDates as $ModDate) {
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
That foreach will iterate only once because the line right above unsets the array it's iterating over.
In case it's a mistake and you in fact wanted to unset $ModDate :
- That will teach you to use variables with names you can differenciate
- That wouldn't want anyway because $ModDate is a copy of an entry of $ModDates, not that entry itself. Unseting it changes nothing in $ModDates.
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
}
I added the two last curly brackets, I don't know if you pasted wrongly or if you simply forgot to put them in your code.
I'm attempting to utilize 2 mysql tables via php/mysql 2 get me a max value. I'm assuming using an array is the correct way to do this, but I've been spending many hours and am missing something.
My tables are:
1) plantcomp, where I want to know all the CompressID listings that have a CustID of $CustID. (there are currently 3).
2) comps, where I want to use those CompressID listings to know the valid Compressor #s. I'll then do a max() on those values so I can name the next compressor max()+1.
My code attempts...This gets me an error: "Notice: Array to string conversion in (pathname) on line 55", then "Array"
//have the custid
echo $CustID;
//under table `plantcomp`, find matching compressid's.
$q55 = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
// Run query
$result55 = mysql_query($q55);
while($row = mysql_fetch_array($result55)){
echo "<p>".$row;
I also tried this, mysql_fetch_assoc, but it only gives me 2 of my 3 valid entries...
$get = mysql_query("SELECT CompressID FROM plantcomp WHERE CustID = '$CustID'");
$money = mysql_fetch_assoc($get);
while($money = mysql_fetch_assoc($get)){echo $money['CompressID'];}
Thank you in advance for your assistance!!
Please change this line
echo "<p>".$row;
to
echo "<p>";
print_r($row);
The problem you have comes from the fact that you are mixing a string (<p>) with an array ($row).
echo "<p>".$row;
You can print the $row array by using print_r:
print_r($row);
You can also access different elements of the $row array (table columns) like this:
$row['column_name'];
For example, lets say your table consists of two columns: first_name and last_name. You can print them like this:
echo '<p>' . $row['first_name'] . ' ' . $row['last_name'] . '</p>';
So, with that knowledge, we can print your CompressIDs:
$result55 = mysql_query("SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "'");
while ($row = mysql_fetch_assoc($result55))
{
echo '<p>' . $row['CompressID'] . '</p>';
}
$CompressID = array(); //Initialising an array
$query = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
$result = mysql_query($query);
while($obj = mysql_fetch_assoc($result)){
$CompressID = $obj['CompressID']; //Storing all the CompressID in an array
echo $obj['CompressID']; // sanity check
}
First run the above query and compare result with db.If the result is not matching
1)There is some wrong data in db
2)Alter your query to get desired result.
If this is working then add rest of the code
if( count($CompressID) >0 ){
$query = "SELECT max(CompressID) as maxCompressID FROM `comps` WHERE `CompressID` IN($CompressID)";
$result = mysql_query($query);
while($newObj = mysql_fetch_assoc($result){
echo $newObj['maxCompressID'];
}
}
I have name1, name2, name3 in mysql how do a do a 'for loop' to retreive the names of each person in mysql which i need to do for my form validation.
<?php
$row2 = "SELECT * FROM user WHERE username = '" . mysql_real_escape_string($_SESSION['username']) . "'";
$result = mysql_query($row2) or die("Error in SQL: " . mysql_error());
$row3 = mysql_fetch_array($result);
?>
In the form, I'm using the following, but it is not retrieving the names:
for($i=1; $i<=5; $i++)
// form code
<?php echo $row3['name'+[$i]]?>');
mysql_fetch_array() returns both numeric and associative keys by default, so your incremental for loop won't give you what you want. Instead, use the MYSQL_ASSOC option or mysql_fetch_assoc()
$row3 = mysql_fetch_assoc($result);
// OR
$row3 = mysql_fetch_array($result, MYSQL_ASSOC);
The for loop has to be done in PHP. It is difficult to tell if your loop is client side or server side.
<?php
for ($i=1; $i<=5; $i++) {
// not 'name' + $i -- PHP uses '.' for concatenation
// but it is easier to interpolate it in double quotes.
echo $row3["name$i"];
}
?>
Update
Since you were trying to mix PHP into a JS loop (which won't work), I recommend instead creating a JavaScript array using PHP, which can then be used in the JS loop later.
<?php
// Open a JS array called namesArray
echo "var namesArray = [";
$names = array();
for ($i=0; $i<=5; $i++) {
// get all the column values into an array
$names[] = '"' . $row3["name$i"] . '"';
}
// Make it into a string
$names = implode(',', $names);
// Close the JS array
echo $names . "];"
?>
That should output something like:
var namesArray = ["val1","val2","val3","val4","val5"];
In your JavaScript loop (which you don't have to change), access the values like:
// Updated to use i-1 instead of i
alert('Please make your colour & shade selection for ' + namesArray[i-1]);
The for loop needs to be inside the php tag.