Export data from mysql into text file? - php

I am trying to export some data from a mysql table into a text file.
However, I only get a few , written into my text file without the actual data in the members table!
I am using the code bellow:
<?php
$fh = fopen('email-data.txt', 'w');
include "../config/connect.php";
/* insert field values into data.txt */
$sql = "SELECT * FROM members";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$num = mysqli_num_fields($query) ;
$last = $num - 1;
for($i = 0; $i < $num; $i++) {
fwrite($fh, $row[$i]);
if ($i != $last) {
fwrite($fh, ",");
}
}
fwrite($fh, "\n");
}
fclose($fh);
?>
could someone please help me out with this?

Change MYSQLI_ASSOC to MYSQLI_NUM
You are fetching rows with Numbers But using an Assiciative array

something like this? you receive an assoc array, without numeric indices
<?php
$fh = fopen('email-data.txt', 'w');
include "../config/connect.php";
/* insert field values into data.txt */
$sql = "SELECT * FROM members";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
//$num = mysqli_num_fields($query) ;
//$last = $num - 1;
//for($i = 0; $i < $num; $i++) {
$last = sizeof($row)-1;
$i = 0;
foreach($row as $field) {
fwrite($fh, $field);
if ($i != $last) {
fwrite($fh, ",");
}
$i++;
}
fwrite($fh, "\n");
}
fclose($fh);
?>

Change the second argument of mysqli_fetch_array() function.
While loop should look like while($row = mysqli_fetch_array($query, MYSQLI_NUM)){...}

Related

Multiple for-loops from one $result = $conn->query($query)

I have imported data into a table and I am now accessing that data with PHP using the code as follows,
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->close();
$conn->close();
This works!
I am really just curious why adding a second for-loop does not work, unless I declare $result again?
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . 'Flag<br/>';
}
$result->close();
$conn->close();
Doesn't work, although 'Flag' is printed an appropriate number of times.
Whereas if I declare $result again.
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result = $conn->query($query);
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
$result->close();
$conn->close();
The code does work.
I have tried unsetting a few variables with unset($row) etc and I did notice if I remove the line,
$row = $result->fetch_array(MYSQLI_ASSOC);
from the second for loop, it will print the last value in the Number column as many times as the loop will run.
I hope that is understandable. I am wondering what is happening in the code that I need to re-declare $result if I want to run a second for loop against it.
The standard solution I would recommend is to do fetch_all()
Instead of:
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
Do
$rows = $result->fetch_all();
foreach ($rows as $row)
{
...
}
// then you can re-loop same array of $rows
foreach ($rows as $row)
{
...
}
There is an internal pointer when you call fetch_* function.
In your first for loop, you send the pointer to the end of the result set.
So, the next fetch will return nothing.
If you run $result->data_seek(0) you will reset this pointer and can reuse:
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->data_seek(0); //<---- REPLACE HERE
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
Of course, usually there is no need to loop the same result set twice, you may need to rethink your logic and loop only once.

Making multiple mysqli queries using a for loop

I'm trying to make a series of mysqli queries by looping through the values of an array - (called column) - but nothing is being returned.
for ($i = 0; $i < sizeof($column); $i++)
{
$mutualInterests = mysqli_query ($conn, "SELECT USER_1 FROM INTERESTS WHERE answer = " . $column[$i] );
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo " $row[USER_1]";
}
}
Just replace your given code with following and see result ..........
$query='SELECT USER_1 FROM INTERESTS WHERE answer ="'.$column[0].'"';
for ($i = 1; $i < sizeof($column); $i++)
{
$query.=' OR answer ="'.$column[$i].'"';
}
$mutualInterests = mysqli_query ($conn,$query);
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo " $row[USER_1]";
}
Replace this:
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo " $row[USER_1]";
}
with this:
$count = 0;
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo $row[$count]."<br>";
$count++;
}
Let me know if it works now! :)

How to store table Field(column) name into An Array?

This is the my code and I am trying to store the value into the Array.
$result = $cid->query("SHOW COLUMNS FROM commissions");
echo $count = $result->num_rows;
while ($row = $result->fetch_assoc()) {
echo $row['Field'];
echo "<br/>";
}
I am trying to do this $ar[]=$row; but there is nothing display !!
$result = $cid->query("SHOW COLUMNS FROM commissions");
echo $count = $result->num_rows;
while ($row = $result->fetch_assoc()) {
ar[] = $row;
echo "<br/>";
}
for($i = 0, $i<12, $i++) {
echo ar['field'][0];
}
Nothing Display in the output
You can do following way to store column name into array. Read comment after every line
For PDO
$rs = $cid->query('SELECT * FROM commissions');// your query
for ($i = 0; $i < $rs->field_count(); $i++) {/// count nu of column
$col = $rs->fetch_fields()($i);//Returns metadata for a column in a result set
$columns[] = $col['name'];// get name from metedata
}
print_r($columns);
For mysqli
$rs = $cid->query('SELECT * FROM commissions');// your query
$col = $rs->fetch_fields();//Returns metadata for a column in a result set
foreach ($col as $val) {
$columns[]=$val->name;
}
print_r($columns);

Delete database tables with php\mysql

I am trying to list all the tables in a database into an array and then proceed to delete the tables contents. What is wrong with my code?
<?php
mysql_connect('localhost', 'root','');
mysql_select_db(database_name);
$res = mysql_query("SHOW TABLES");
$tables = array();
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$tables[] = "$row[0]";
}
$length = count($tables);
for ($i = 1; $i < $length; $i++) {
$res = "DELETE FROM $tables[$i]";
mysql_query($res);
echo $res;
$i++;
}
?>
At the end of your for loop you don't need to do $i++; anymore, as this operation is already included in the for loop.
The code you have at the moment will delete the contents of one table and then skip a table, delete contents of one table again and skip one again...
Also $i should start with 0 as the first element in an array in php is element 0.
for ($i = 0; $i < $length; $i++) {
$res = "DELETE FROM $tables[$i]";
mysql_query($res);
echo $res;
}

how do I traverse rows in a table

I have a table named members with 3 rows. The following code attempts to display all the rows in the members table. It displays the 1'st record 3 times instead of displaying each record once.
<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
$keysarray = array_keys($array);
$valuearray = array_values($array);
for ($i=0; $i < $num; $i++) {
for($j = 0; $j < count($array); $j++) {
echo "<table>";
echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
mysqli_close($con);
?>
I've updated this per suggestions:
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
while ($row = mysqli_fetch_assoc($res)) {
foreach($array as $key => $value){
echo "<table>";
echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
That's because, your $num = 3, count($array) = 3 and the outer for loop has no bearing on inner for loop.
Where you have $array = mysqli_fetch_assoc($res);, you will only receive one row from your database. You need something like:
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
}
Any basic tutorial will tell you this. Even the PHP docs provide an example.
you can use do something like this..
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
e.g
echo $row['id'];
echo $row['name'];
etc
}
try this... this peace of code is not tested but just to give you an idea...
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
echo "<table>";
echo '<tr><td> id = "'.$row['id'].'":
</td><td> name = "'.$row['name'].'"</td></tr>";
echo "</table>";
}

Categories