I have searched for similar questions but cannot find the right answer to my specific one. I have a column (data) in my table (table) which contains comma separated values which are id's e.g.
Row 1= 4,5,45
Row 2= 5,8,9
Row 3= 5
I use an in_array function to retrieve the number of occurances for the $data value within the while loop. So I use an sql function to retrieve the number of times a certain value such as '5' occurs in all rows within the while loop.
The issue is that I can only retrieve the $data value if it is by itself (i.e. no commas just the integer by itself) so based on my example in the list, I can only retrieve 5 once (row 3). I would like to retrieve the value '5' three times as it appears in all the rows. Here is my code below and any help would be appreciated. The $selectiontext variable is what the user enters from the form.
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
}
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
Thank you.
you keep overwriting the variables $datacheck and $id, leaving you with only the last version of them. move that curly brace down two lines, like this:
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
}
I am not totally sure of your requirements, is not very clear what you intend to do as part of the code is missing.
I assume you want to check each row of a comma separated of a CSV file ($frnd_arry_mem1 being the row) against your data in column data, if any of those comma separated data (not) occurs.
Assuming you are already looping through your CSV, this would be the code (non tested):
NOTE: might be inefficient retrieving data within a loop, if you can do otherwise - but I cant tell as I dont kow the full specs of your script.
If I got the specs wrong please clarify, I will try to help further.
$sql = "SELECT data, id
FROM table
WHERE data='$selectiontext'";
$sql_frnd_arry_mem1 = mysql_query($sql);
$results = array();
// get values to check
while ($row = mysql_fetch_array($sql_frnd_arry_mem1))
{
$results[] = array(
'datacheck' => $row["data"],
'id' => $row["id"],
);
}
foreach ($results as $result)
{
$frndArryMem1 = explode(",", $frnd_arry_mem1);
$data = explode(',', $result['datacheck']);
foreach ($data as $d)
{
if (($frnd_arry_mem1 !=="") && (!in_array($d, $frndArryMem1)))
{
echo 'DEBUG: Record #' . $id . ' not found, value:' . $d . '</br>';
}
}
}
Related
I'm having difficulty achieving this one, so thought I'd ask..
I have a table which contains some field names. Each field entry in the table has a type, a name and an ID as per the norm.
I'd like to be able to group my SQL results so that I can 'print' each type (and the type's associated members) into a table. I tried the following:
$query = "SELECT id,type,opt_name FROM fields ORDER BY type";
$resource = $pdo->query($query);
$results = array();
while ( $row = $resource->fetch() ) {
$type[$row['type']] = $row['opt_name'];
$o_id = clean($row['id'], 'text');
$o_name = clean($row['opt_name'], 'text');
}
foreach ($type AS $o_type => $o_name) {
echo $o_type;
echo "<br>";
foreach (($type) AS $opt_name) {
echo $opt_name;
echo "<br>";
}
}
Please try not to worry too much about the HTML output, it's just for this example to show context.
When the code is executed, it will only print one row. As a result, I have 'print_r' tested both:
$type[$row['type']] = $row['opt_name'];
Which does indeed show only one row in the array. Creating:
$results = $row;
Shows all the data, but too much of it and not in the way I think will work with the 'foreach'.
I'm probably making a rookie mistake here, but can't see it.
Help!
You're going to be overwriting the value of $type['type'] instead of pushing more values onto it with:
$type[$row['type']] = $row['opt_name'];
You most likely want
$type[$row['type']][] = $row['opt_name'];
Then you'll need to fix your loop so you loop through the options, not the types twice.
foreach ($type AS $o_type => $options) {
echo $o_type;
echo "<br>";
foreach ($options AS $opt_name) {
echo $opt_name;
echo "<br>";
}
}
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
i have a mysql table the contains an index id, a data entry and 10 other columns called peso1, peso2, peso3...peso10. im trying to get the last 7 peso1 values for a specific id.
like:
$sql = mysql_query("SELECT * FROM table WHERE id='$id_a' ORDER BY data DESC LIMIT 0, 7");
when i try to fetch those values with mysql_fetch_array, i get all values together.
example:
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'];
}
i get all peso1 values from all 7 days together. How can i get it separated?
They will appear all together because you are not separating them as you loop through them.
for example, insert a line break and you will see them on separate lines
while($line = mysql_fetch_array($sql)) {
echo $line['peso1'] ."<br />";
}
You could key it as an array like so
$myArray = array();
$i = 1;
while($line = mysql_fetch_array($sql)) {
$myArray['day'.$i] = $line['peso1'];
$i++;
}
Example use
$myArray['day1'] // returns day one value
$myArray['day2'] // returns day two value
It's not clear what you mean by "separated" so I'm going to assume you want the values as an array. Simply push each row field that you want within your while loop onto an array like this:
$arr = array();
while($line = mysql_fetch_array($sql)) {
$arr[]=$line['peso1'];
}
print_r($arr);//will show your peso1 values as individual array elements
RESOLVED
I have used the answer from alfasin, but as that gave me WAY too much information, i wrote a little script to just get the field names. As the field names apeared first, it was rather simple:
$here = array();
$SQL = "SHOW COLUMNS FROM User";
foreach($conn->query($SQL) as $row) {
$here[] = $row[0];
}
echo '<pre>';print_r($here);echo '<pre>';
This left me with the new array $here containing the column names, hope this helps someone in the future :)
Original question:
Let me clarify a bit, I have a mysql table and I'm trying to select * from it, and display the result in an html list <ol>. I can manage to grab the row data JUST FINE, but I cannot for the life of me figure out how to grab the table column names, in order to match them up with the row, respectively. this is my code that is grabbing the row data:
//get those results
$sql = "SELECT DISTINCT *
FROM User
WHERE Owner = '".$owner."'";
foreach($conn->query($sql) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
$u = 1;
for($i = 2; $i <= $halfHax; $i++){
echo $row[$u].'<br>';
$u++;
}
}
this is giving me all the result where Owner == $owner just like it should, but I would like the column names to list with those, I could hard-code it out, but more columns may be added/changed so I would rather not. Any ideas?
Try:
SHOW COLUMNS FROM mytable
http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
Fetch rows as associative arrays in order to keep your column names as array keys.
Here's my suggestion:
$sql = "SELECT DISTINCT * FROM User WHERE Owner = :owner";
$sth = $conn->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':owner' => $owner);
while($row=$sth->fetch(PDO::fetch_assoc) as $row) {
//split array in half
$hax = count($row);
$halfHax = $hax / 2;
//set up a for loop to give results
foreach ($row as $key => $value) {
echo $key.'='.$value.'<br />';
}
}
To just list the column names:
array_keys($row);
Please refer to SHOW COLUMNS at the MySQL Reference if you want more information about the columns.
But I'd suggest using mysqli_fetch_assoc and then using foreach (array_expression as $key => $value) to get the column name and it's value, for each row.
I have a mysql table with columns id, f1, f2, f3, ..., f20 where id is productID and f1,...f20 are product features. Depending on each product, some might have all, none or only some columns filled.
Each column holds a delimited string like a#b#c#d where a,b,c,d are values in different languages (a=english, b=french etc)
I need to select a row by it's id, explode each column's value (f1,f2...) with '#' in order to get the language part I need and then pass the values to an array in order to use in my product spec page.
How do I loop through the fetched row (i'm using $row = my_fetch_array) and put the exploded value into a one dimension array like $specs=('green', 'M', '100', 'kids'...) etc?
PS:I know, is complicated but I cant come up with a better idea right now.
Try this:
$result = mysql_query("...");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$arr = array();
foreach ($row as $k=>$v)
{
$features = explode("#", $v);
$value = $features[1]; // get the specific language feature
$arr[] = $value;
}
$specs = join(", " , $arr);
}
Not sure this is the best way togo but you could define an array with your langs, then access the result by lang
<?php
$langs=array('eng'=>0,'fr'=>1,'ger'=>2,'geek'=>3);
while ($row=mysql_fetch_assoc($result)) {
$specs=explode('#',$row['f1']);
$other=explode('#',$row['f2']);
...
}
//Get lang from cookie that you could set elsewhere
$lang=(isset($_COOKIE['lang']))?$_COOKIE['lang']:'eng';
echo $specs[$langs[$lang]];
?>
My solution for how I understand you question:
// Make a MySQL Connection
$sQuery = "SELECT f1,f2,... FROM table WHERE id = ...";
$oResult = mysql_query($sQuery) or die(mysql_error());
//Fetch assoc to use the column names.
$aRow = mysql_fetch_assoc($oResult);
//Prepare the product properties array
$aProductProperties = array("English"=>array(),"French"=>array(),"Dutch"=>array());
//Loop over all the columns in the row
foreach($aRow as $sColName=>$sColVal){
//Explde the column value
$aExplodedCol = explode("#",$sColVal);
//The code below could be nicer when turned into a looped that looped over every language,
//But that would make the code less readable
$aProductProperties['English'][$sColName] = $aExplodedCol[0];
$aProductProperties['French'][$sColName] = $aExplodedCol[1];
$aProductProperties['Dutch'][$sColName] = $aExplodedCol[2];
}
//Done, you should now have an array with all the product properties in every language