how to split the data into array? - php

I have stored the data in a mysql database, I want to know how I can split the data in each different array before output them in php?
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$qrytable1="SELECT id, mydata FROM mydb ";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
}
?>
On my PHP page it show something like this:
<tr><td>my data 1</td></tr><tr><td>my data 2</td></tr><tr><td>my data 3</td></tr><tr><td>my data 4</td></tr>
I want to split them up by turn into array and output them with each different array to something like this:
mydata1
mydata2
mydata3
mydata4
How I can split the data into array before I could output them in my php?

Are you looking for something like this?
(consider it as an example, but, as #BenM, consider using PDO)
$sql = 'SELECT * FROM country';
$query = mysql_query($sql);
$countries = array();
while ($country = mysql_fetch_assoc($query)){ $countries[] = $country; }
This will allow you to use
foreach ($countries as $country) {
echo $country['name'];
}

Your data is already in an array. That's what this line does:
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
If you need to access the array outside of the while loop you could do this..
$myArray = array();
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$key] = $val;
}
}
actually.. assuming your query returns multiple rows it would be a multidimensional array..
$myArray = array();
$i = 0;
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$i][$key] = $val;
$i++;
}
}

If I am right than along with getting data in array you want to remove the space in between the data
try this
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
$myArr[] = $row['mydata'];
}
foreach($myarr as $key=>$value)
{
$myArr[$key] = str_replace(" ","",$value);
}
str_replace will remove the spaces.

You can used this,
$db->setQuery($query);
$rows = $db->loadObjectList();
$i=0;
foreach($rows as $row){
//$row;
$image = json_decode($row->images);
// split code
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
$replace = '';
$introtext = str_replace($order, $replace, $str);
$introtext_split = explode("|", $introtext);
$data[0]->designation = preg_replace('#<br />?#', "\n", $introtext_split[0]);
$data[0]->description = preg_replace('#<br />?#', "\n\n", $introtext_split[1]);
$data[0]->small_description = preg_replace('#<br />?#', "\n\n", $introtext_split[2]);
}
In data used any tag, Or this tag replace using following section :
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
I think its useful to you.

Related

implode output does not gives proper output

This shows all the elements from an array in a string but without a separator. I used ',' as a separator in this code. And it does not work. How can i separate them with separator.
$con = mysql_connect("localhost","root","");
if(!$con)
{
die("Database Connection failed.".mysql_error());
}
$db = mysql_select_db("test1",$con);
if(!$db)
{
die("Database selection failed.".mysql_error());
}
$query = "select * from menu limit 10";
$result = mysql_query($query,$con);
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
//$menu_name = $row['m_name'];
//$menu_image = $row['m_image'];
$menu_name = array($row['m_name']);
$menu_image = array($row['m_image']);
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
}
if(!$result)
{
echo mysql_error;
}
?>
you are storing array into variable . so if you will use imploade on an variable it will not show the result so best way is to store your result into an array and then use implode .
Don't use depricated mysql_* function use mysqli_* or pdo
instead
$menu_image=array(); // start array to store
$menu_name=array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name']; // store menu name
$menu_image[] = $row['m_image']; // store menu image
}
echo implode(',',$menu_name); // finaly use implode
You can try this:
$menu_name[];
$menu_image[];
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$menu_name[] = $row['m_name']; // I change your $menu_name into an array so that when you fetch $row['m_name'] it returns an array
$menu_image[] = $row['m_image']; //same thing
}
echo implode(',',$menu_name);
//echo "<img src='images/$menu_image' style='height:200px;width:200px;'>";
try this in place of your while loop
$menu_name = array();
$menu_image = array();
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$menu_name[] = $row['m_name'];
$menu_image[] = $row['m_image'];
}
echo implode(',',$menu_name);

Access PHP Generated XML

I'm working on outputting data from MySQL database in XML format, so I made a php file that displays data from database in XML format on the page.
<?php
// Return all existing nid in array (Different types of form);
function nid(){
$query = "SELECT w.nid
FROM webform w";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Return existing rows of corresponding nid
function sid($nid){
$query = "SELECT ws.sid
FROM webform_submissions ws
WHERE ws.nid = $nid";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Return corresponding components of nid;
function cid($nid){
$query = "SELECT wc.form_key
FROM webform_component wc
WHERE wc.nid = $nid
ORDER BY wc.cid ASC";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Return values of fields corresponding to nid and sid
function data($nid, $sid){
$query = "SELECT wsd.data
FROM webform_submitted_data wsd
WHERE wsd.nid = $nid AND wsd.sid = $sid
ORDER BY wsd.sid ASC";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Define Constants
DEFINE("DB_SERVER", "localhost");
DEFINE("DB_USER", "root");
DEFINE("DB_PASS", "");
DEFINE("DB_NAME", "drupal7");
//Establish Connection
mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");
//Select Database
mysql_select_db(DB_NAME)
or die("Could not connect to the database");
$xml_output = "<?xml version=\"1.0\" ?>\n";
$xml_output .= "<schema>";
foreach (nid() as $nid){
$xml_output .= "<form fid=\"$nid\">\n";
foreach (sid($nid) as $sid){
$xml_output .= "<row rid=\"$sid\">\n";
for ($i = 0; $i < count(cid($nid)); $i++){
$tag_array = cid($nid);
$value_array = data($nid, $sid);
$tag_row = $tag_array[$i];
$value_row = $value_array[$i];
$xml_output .= "<$tag_row>\n";
$xml_output .= "$value_row\n";
$xml_output .= "</$tag_row>\n";
}
$xml_output .= "</row>\n";
}
$xml_output .= "</form>\n";
}
$xml_output .= "</schema>";
header("Content-type: text/xml");
echo $xml_output;
mysql_close();
?>
But I can't see to find a way to access the XML data or download it as XML file.
Here's how the output looks like when I run it.
Thanks in advance
Don't use strings to build your xml data. You should be using something like SimpleXMLElement
See How to generate XML file dynamically using PHP?
Instead of:
$table[] = $row[0];
Try using the array_push function:
array_push($table,$row[0]);

Storing the result of an SQL call in a php variable

I have the code below and it's working as it should however instead of echoing the results to the screen, I need to store the results in a php variable called $var. How would I go about doing that?
<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
echo $row['id_member'];
}
mysql_close($con);
?>
Depending on what you want to achieve here is a few possible ways of doing this
$var = "";
while ($row = mysql_fetch_array($result)) {
$var .= $row['id_member'] . "\n";
}
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}
replace echo with $var[].
That will push each result onto the end of the array. It would probably be good to define the variable first.
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}
<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
$v = array(); // $v instead of $var, since var is a keyword and may cause troubles
while ($row = mysql_fetch_array($result)) {
array_push($v, $row['id_member']);
// or
//$v[] = $row['id_member'];
}
mysql_close($con);
?>
If the select statement will return more than one result, then you need to store the values in an array:
$member_ids = array();
while ($row = mysql_fetch_array($result)) {
$member_ids[] = $row['id_member'];
}
If the select statement will return a single result (you can make sure by appending a LIMIT 1 to the value of the $sql variable).
$row = mysql_fetch_array($result);
$member_id = $row['id_member'];

array_push key=>value , how can do it?

I want to push key and value in array , but I can't
$con = mysqli_connect('localhost','root','','wp') or die (mysqli_error('Error:'));
$query = mysqli_query($con,'set names utf8')or die (mysql_error());
$qy = mysqli_query($con,"SELECT ID,post_title FROM wp_posts WHERE post_type='page' AND post_status='publish'")or die (mysql_error());
$arr = array();
while ($row = mysqli_fetch_array($qy)){
$id = "?page_id=".$row['ID'];
$title = $row['post_title'];
$arr[] = $id . "=>" . $title;
array_push($arr, "$id" => "$title");
}
plz help me ..
thanks ^_^
Here's what I would do instead:
$arr = array();
while ($row = mysqli_fetch_assoc($qy)){
$id = $row['ID'];
$arr[$id] = $row['post_title'];
}
And then when you need to print them:
foreach ($arr as $id => $title) {
echo "?page_id={$id}'>{$title}</a>";
// or whatever, depends on how you want to print it
}
Don't store unnecessary information (ie: ?page_id=) in arrays.
Do you want to do $arr[$id] = $title? Or do you want this:
if (!isSet($arr[$id])) {
$arr[$id] = array();
}
$arr[$id][] = $title;
The former will make it so that $arr contains $id=>$title. The latter will make it so that $arr contains $id=>array($title1,$title2,$title3) etc if there are multiples.

php oci_fetch_array and pass value to function issue

1) I want to save case 1 value to an array. Return this array and pass it to a function. The code become case 2, but no result come out, where is the problem?
2) In function display_urls, i want to echo both $url and $category. What should i do in IF condition or add another line of code?
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url."";
echo "".$category."";
}
}
echo "";
}
case 1: work fine
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$i=0;
echo "";
while( $row = oci_fetch_array($result) ){
$i++;
echo "";
echo "".$row['USERNAME']."";
echo "".$row['BM_URL']."";
echo "".$row['CATEGORY']."";
echo "";
}
echo "";
case 2:
$url_array = array();
while( $row2 = oci_fetch_array($result, OCI_BOTH)){
$i++;
$url_array[$count] = $row[0];
}
return $url_array;
I think you probably want something like this:
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url['BM_URL']."";
echo "".$url['CATEGORY']."";
}
}
echo "";
}
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$url_array = array();
while( $row = oci_fetch_array($result, OCI_ASSOC)){
$url_array[] = $row;
}
display_urls($url_array);
This will store all the information on the URLs in $url_array with a lookup by column name.

Categories