while loop not looping with str_pad - php

Im currently trying to do a loop where it will display all the records in the table. but the result that i get now is it display one data which the last record from the table. what should i do if i want to make it display all the records in table and not only one data being display
$myFile = "testFile.txt";
$fo = fopen($myFile, 'w' ) or die ("cant open file");
$header = str_pad($rekod,0).str_pad($organisasi,5).str_pad($jabatan,40).str_pad($tarikh_kredit,8).str_pad($sec_code,16,"0").str_pad($filler,150)."\n";
$sql = "SELECT * FROM pengerusi_johor WHERE negeri='$negeri'";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_array($result))
{
$detail = str_pad($rekod,0).str_pad($bank_code,7).str_pad($row['nombor_akaun'],16).str_pad($row['nama'],40);
}
fwrite($fo,trim($header).PHP_EOL.$detail);
fclose($fo);

In your code you are overwriting the value of $detail each time round the loop with the value in while ..
you should use .= to append each row to your string
while($row = mysqli_fetch_array($result)) {
$detail .= str_pad($rekod,0).str_pad($bank_code,7).str_pad($row['nombor_akaun'],16).
str_pad($row['nama'],40);
}

Related

Create PHP array out of table column

I am trying to create a loop that displays each row in a table. I think I need to make an array out of the PK, but I can't figure out how to do that. Here is my code so far:
$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
$error = $conn->error;
} else {
$data = $allData->fetch_assoc();
$rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
// code to be run for each row
$rowId++;
}
EDIT: Sorry my question is confusing, I'm new to PHP.
Your question is a bit confusing but I think this is what you are trying to do:
$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
$data[$row['PK']] = $row;
}
That would iterate over each row, creating an array and using the row's value for column PK as an associative array key.
fetch_assoc() (I assume mysqli here now) doesn't fetch all data from a result, but one row after each other. So you don't need to make an array of $row['PK'], but need to loop over the results.
$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
$error = $conn->error;
} else {
$cnt=0;
while($row = $result->fetch_assoc()) {
// code to be run for each row
// you can display $row['PK'] now:
echo $row['PK'];
// or add that value to something else, whatever you need
$cnt = $cnt+$row['PK'];
// or to have a new array with the values of one table-column:
$columnRows[] = $row['PK'];
}
// now you can use the created array
foreach($columnRows as $PK) {
echo $PK;
}
}

Remove duplicates from PHP array (array_unique)

I am getting a specific field from 4 different tables.
<?php
//I connect to the database and the 4 tables
// Location of CSV
$location = 'path.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array();
// Read csv file to avoid adding duplicates
$file = fopen($location, 'r');
$data = array();
while($row = fgetcsv($file))
{
$data[] = $row;
}
// Query 1
$sql = ('select distinct(field) as field from '.$table1.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Query 2
$sql = ('select distinct(field) as field from '.$table2.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Query 3
$sql = ('select distinct(field) as field from '.$table3.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Query 4
$sql = ('select distinct(field) as field from '.$table4.'');
// Run the query
$query = $Db->query($sql);
// Check for SQL errors
if ($Db->error)
{
return ($Db->error);
}
// Put data in the list
while ($row = $query->fetch_assoc())
{
array_push($list,array($row['field'], ''));
}
// Save list in the csv file without overwriting
$fp = fopen($location, 'a');
foreach (array_unique($list) as $fields)
{
if (in_array($fields, $data))
{
echo "Duplicate found";
}
else
{
echo "Save to file";
fputcsv($fp, $fields);
}
}
fclose($fp);
?>
In the end I check if the fields are already in the file. The only problem is that I still have duplicates because some tables might have exactly the same field. So, I want to remove the duplicates from the PHP array "list".
I am using :
$cleanlist = array_unique($list);
but I am getting an error:
PHP Notice: Array to string conversion
More specifically the change in my code is :
$cleanlist = array_unique($list);
// Save list in the csv file without overwriting
$fp = fopen($location, 'a');
foreach ($cleanlist as $fields)
{
if (in_array($fields, $data))
{
echo "Duplicate found";
}
else
{
echo "Save to file";
fputcsv($fp, $fields);
}
}
As explain in the docs, array_unique compares elements as strings by default. You are getting this error because PHP is trying to convert an Array to string. You have a 2D array, an array of array.
You can use the flag SORT_REGULAR to compare the elements as they are.
But be careful, only same key/value pairs are considered identicals.
You could reduce amount of code a lot by using UNION in SELECT statement.
SELECT field FROM table1
UNION
SELECT field FROM table2
UNION
SELECT field FROM table3
UNION
SELECT field FROM table4
UNION returns distinct results by default.
That worked :
$list = array_map("unserialize", array_unique(array_map("serialize", $list)));
The $list is a 2d array.

mysql select into array twist

I have 10 rows, however when I do the following, it's only giving me the last row. Any kind of help I can get on this is great appreciated!
$query = "select * FROM `$table`.`channels` WHERE `country`='vietnam' ORDER BY `chanid`";
$result = mysql_query($query,$db) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($result)) {
$chanid = $row['chanid'];
$data[navtitle] = "$chanid - $row[title]";
$data[navurl] = "http://www.localhost.com/vietnam.php?chanid=$row[chanid]&country=$row[country]";
$data[vid_art] = "$chanart";
}
$array2=array_merge(array($array,array($data));
$JSON=json_encode($array2);
echo $JSON;
My $data array is only outputs the last row of my mysql fetch. How can I get it to pull out all 10 rows that I have?
Each time you go through the
while($row = mysql_fetch_array($result)) {
loop, you're setting $data to a new value.
This means it'll only ever contain the last row's worth of data.
Your code should look something like this.
$array2 = array();
while ($row = mysql_fetch_array($result)) {
$data = array();
$chanid = $row['chanid'];
$data['navtitle'] = "$chanid - $row[title]";
$data['navurl'] = "http://www.localhost.com/vietnam.php?chanid=$row[chanid]&country=$row[country]";
$data['vid_art'] = $chanart;
$array2[] = $data;
}
$JSON = json_encode($array2);

Storing database records into array

I would want to create an array that will hold records retrieved from a database using a query of SELECT statement.
The records to be retrieved have multiple fields such as lastname, firstname, mi and 20 more fields. What would be the best approach on coding this function?
alright i have followed what prisoner have given below.. the next question is how do i search through this kind of array using queries? for example i want to search for a username..
<?php
// run query
$query = mysql_query("SELECT * FROM table");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['username']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}

How to write array values into a csv file in PHP?

I have an array whose structure is like $data = array{0=>'abc',1=>xyz,2=>tqs}
Now I need to write these values into a csv file. I need to display every value in 1st column and with everytime new row on new insert along with previous value already available.
Below is the code I am using but everytime I execute it I get the last value in the file:
for ($c=0; $c < $num; $c++) {
echo $data[$c];
echo $query = "select prod_sku,prod_name
from
tbl_product
where
prod_sku = '".$data[$c]."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if(empty($row)){
print_r($row);
echo 'test';
$fp = fopen("file.csv", "w");
print_r($data[0]);
fputcsv($fp, $data[0]);
fclose($fp);
}
How can i achieve this using PHP?
The problem is that you are doing fopen inside the for loop, so every time the loop runs, your file gets re-written. Move the fopen and fclose outside of the loop and it will work. Like this;
$fp = fopen("file.csv", "w");
for ($c=0; $c < $num; $c++)
{
$query = "select prod_sku,prod_name from tbl_product where prod_sku = '".$data[$c]."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
fputcsv($fp, $data);
}
fclose($fp);
If you use MySQL you could use SELECT ... INTO OUTFILE:
SELECT prod_sku, prod_name
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM tbl_product
WHERE 1
http://dev.mysql.com/doc/refman/5.0/en/select.html

Categories