explode/implode from database php - php

I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.

You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';

First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}

Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}

Related

getting duplicated results from nested foreach loop

I'm trying to get the following output from mysql for Google Line Chart API:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
I have set up several input checkboxes to send field names (e.g width,diameter) to the database via $_POST["info"] and retrieve the values from those fields. Here's the part that generates the data from mysql:
$result = $users->fetchAll();
$comma = "";
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
My desired output should be like this:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
But that code is generating duplicated results like this
[["product","diameter","width"],["Product 1","24"],["Product 2","24,4,8"]]
I guess I shouldn't be using the nested foreach to loop over $_POST. Can anyone tell me how to fix that?
Full PHP Code:
$info = $_POST["info"]; // It contains an array with values like width,diameter,thickness etc...
$comma = "";
foreach($info as $in)
{
$field .= "".$comma."b.".$in."";
$comma = ",";
}
$sql = "
SELECT {$field},a.user_id,a.name
FROM `product_detail` a INNER JOIN
`attr` b ON a.model = b.model
WHERE a.user_id = ?
GROUP BY a.model
";
$users = $dbh->prepare($sql);
$users->bindValue(1, $_SESSION["user_id"]);
$users->execute();
$result = $users->fetchAll();
$comma = "";
$data="";
$i = 1;
$data[0] = array_merge(array(product),$info);
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p];
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
$_POST["info"] Content:
Array
(
[0] => diameter
[1] => width
)
try it like this:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d[]=$r["name"];
foreach($_POST["info"] as $p)
{
$d[]= $r[$p];
}
$data[$i] = $d;
$d=array(); //set $d to empty not to get duplicate results
$i++;
}
echo json_encode($data);
The end result you are looking for, is valid JSON. You should not try to manually generate that.
Instead you should make an array of arrays in php and use json_encode($array) to get the result you are looking for.
Also note that by injecting your POST variables directly in your query, you are vulnerable to sql injection. When accepting fields, you should check them against a white-list of allowed values.
Try the below solution:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d = array();
foreach($_POST["info"] as $p)
{
$d[] = $r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$data[$i] = array($r["name"]) +$d;
$i++;
}
echo json_encode($data);

PHP: When using explode() twice, how to auto increase

I was trying something but I need to explode it twice because I store 2 variables in a string. Anyways, I used a while loop but I don't understand, I use cid++, but it does not appear to increase. ANyways, here's the code.
$cid = 0;
while($row = mysql_fetch_array($result)){
$comment = explode("-", $row['comments']);
$madeby = explode("///", $comment[$cid]);
$cid++;
echo $madeby[1];
}
Since you're setting a var and incrementing you can use it as a key for both arrays.
$cid = 0;
while($row = mysql_fetch_array($result)){
$comment[$cid] = explode("-", $row['comments']);
$madeby[$cid] = explode("///", $comment[$cid]);
echo $madeby[$cid][1];
$cid++;
}
Then you can do this:
foreach($madeby as $key=>$tempArr){
echo '"'.$madeby[$key][0].'" by "'.$madeby[$key][1].'"<br>';
}
To see the whole array:
print_r($madeby);
try this
while($row = mysql_fetch_array($result))
{
$comment = explode("-", $row['comments']);
foreach($comment as $each_comment)
{
$madeby = explode("///", $each_comment);
echo $madeby[1];
}
}
or if you really want to use cid then
while($row = mysql_fetch_array($result))
{
$comment = explode("-", $row['comments']);
for($cid=0;$cid<count($comment);$cid++)
{
$madeby = explode("///", $comment[$cid]);
echo $madeby[1];
}
}
try this:
while($row = mysql_fetch_array($result)){
$comment = explode("-", $row['comments']);
$cnt = count($comment);
$madeby = array();
for($cid=0; $cid<$cnt; $cid++){
$madeby[] = explode("///", $comment[$cid]);
}
print_r($madeby);
}

trying to add seperator in alphabetically sorted list wen first letter will change

I sorted a list alphabetically and data from database mysql.To read the data i am using foreach loop.Now,I want when first letter (a->b->c) will change a seperator will be add after 'A' character list and so on.
Code:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
echo $val['name']."<br>"; echo "<hr></hr>";
}
Thanks in advance
<?php
$first = '';
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
foreach($result as $val){
$first = substr($val['name'], 0, 1);
if ($first != $prev){
echo '<h1>'.$first.'</h1>';
}
echo $val['name']."<br>";
$prev = $first;
}
Try this:
$result = mysqli_query($con,"SELECT * FROM pages order by name ASC");
$lastChar = "?"; //initialization
foreach($result as $val){
if($lastChar != $val['name'][0]){
echo $val['name'][0].'<BR>'; //separator
}
echo $val['name']."<br>"; echo "<hr></hr>";
$lastChar = $val['name'][0]; //update
}
Try this (untested code) :
$firstLetter = 'A';
foreach( $result as $val ) {
$ch = substr( $val['name'],1,1);
if( $ch != $firstLetter ) {
echo "<hr>";
$firstLetter = $ch;
}
echo $val['name']."<br>";
}
$char = 'a';
foreach($result as $val) {
$newChar = substr($val['name'],0,1);
if ($newChar != $char) {
$char = $newChar;
echo "seperator for new character";
}
//do your other stuff
}
Is this what you were wanting to do?

HTML select not inflating correctly from PHP array

I am trying to create a drop down menu of usernames or a <select> as it's known in HTML. However I am only getting the last value back from my array and I can't figure out why.
PHP
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
HTML
<select>
<?php $names = getUserName($db); foreach($names as $key => $value) { ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option>
<?php }?>
</select>
I'm fairly sure the HTML section of my code is solid. I think the error lies in how I'm adding values to my $names array but after staring at it for a half an hour I can't see it. Thanks for any help/fresh eyes.
You need to declare your array outside the loop
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
this is emptying your array every time : $names = array();
use this :
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
You are creating a new $names array every row then returning the last one. You need to declare the array outside the while loop. The following should work:
function getUserName($db) {
try {
$sql = 'SELECT members.name FROM members';
$query_an = $db->query($sql);
$count = $query_an->rowCount();
if ($count > 0) {
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
The problem is you're re-initializing the array on every loop:
See:
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names = array();
$names[] = $row['name'];
}
return $names;
Should be:
$names = array();
while ($row = $query_an->fetch(PDO::FETCH_ASSOC)) {
$names[] = $row['name'];
}
return $names;

Exclude last comma in php array

I have a simple database connection:
$rowdata = mysql_query("SELECT * FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo "".$row['name'].",";
}
I would like it to print out:
Adam, Sophia, Tom, Brian
instead of:
Adam, Sophia, Tom, Brian,
How do I exclude the last comma in the best way?
$rowdata = mysql_query("SELECT name FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode(', ', $names);
Instead of echoing it straight out, put it into a variable (named $values perhaps) then do:
$values = rtrim($values,",");
Print the comma before each entry and omit the first one:
$first = TRUE;
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
if(!$first) echo ',';
echo htmlspecialchars($row['name']);
$first = FALSE;
}
Another way would be to use extract echoing the first line from the loop, that way the if statement does not have to be evaluated each iteration (premature optimization ftw!):
if(($row = mysql_fetch_array($rowdata)) !== FALSE)
echo htmlspecialchars($row['name']);
while(($row = mysql_fetch_array($rowdata)) !== FALSE) {
echo ',', htmlspecialchars($row['name']);
}
And finally you can do it in mysql:
select group_concat(name) from table_names
In full this would become:
$rowdata = mysql_query("SELECT group_concat(name) as names FROM table_names");
while($row = mysql_fetch_array($rowdata)) {
echo $row['names'];
}
$rowdata = mysql_query("SELECT * FROM table_names");
$names = array();
while($row = mysql_fetch_array($rowdata)) {
$names[] = $row['name'];
}
echo implode( $names, ',' );
By the way, if you're only using the 'name' column, it's better to do SELECT name FROM ..
Make it ..
$names = array();
while ( $row = mysql_fetch_array( $rowdata ) ) {
$names[] = $row['name'];
}
$names = implode(', ', $names);
echo $names;

Categories