php export sqlite table to csv - php

I'm trying to export a table to a CSV file using php and it's working with the following code:
while($row = $results->fetchArray()) {
print '"' . stripslashes(implode('","',$row)) . "\"\n";
}
However, it creates duplicates of each field when I view the CSV file. I don't know how to limit them down to one per field.

This is because SQLite3Result::fetchArray by default fetches both a numeric and a named index for each column in the result. So $row might look like this:
array(
0 => 'Fred',
'firstname' => 'Fred',
1 => 'Jones',
'lastname' => 'Jones',
2 => 'fredjones#example.com',
'email' => 'fredjones#example.com'
)
The way around this is to specify other behaviour in the fetchArray call by passing a constant:
while ($row = $results->fetchArray(SQLITE3_ASSOC)) {
This means that only the names of the columns will be fetched. Equally, you could do SQLITE3_NUM: in your case it would make no difference.
Note also that a nicer way to output CSV data is with the fputcsv method, which handles enclosure and escaping as necessary. It requires a file handle: if you just want to echo the data, you can use the STDOUT constant:
fputcsv(STDOUT, $row);
Running example

fetchArray returns both associative and numeric indices by default. To return only numeric indices use:
while($row = $results->fetchArray( SQLITE3_NUM )) {
Or to return an associative array use:
while($row = $results->fetchArray( SQLITE3_ASSOC )) {

Related

PHP-JQuery-Ajax: How to Populate table with all results from mysql query result (json encoded array)

I've been trying to figure out how to load the results of a search into a table but no matter what I do, I'm only getting one single result instead of the 2 (sample size) rows that I have in the table in the db.
This is the MySQL Code:
if (isset($_POST['search_value'])) {
$search_value = mysqli_real_escape_string($conn, $_POST['search_value']);
$sql = "SELECT
record_id,
personal_id,
name,
status,
entry_date
FROM sample_db
WHERE EmpID = '".$search_value."'";
$res = mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
$data = array();
while($row = mysqli_fetch_array($res)){
$data = array(
'tb_record_id' => $row['record_id'],
'tb_personal_id' => $row['personal_id'],
'tb_name' => $row['name'],
'tb_status' => $row['status'],
'tb_entry_date' => $row['entry_date'],
);
}
echo json_encode($data);
}
I've read several examples where the array is built as $data[] = array( data goes here) instead of $data = array(data goes here) but whenever I try $data[], it doesn't return anything to the table BUT the console log does show all the results within the array.
also, using dataType: 'json' doesn't seem to work either.
The only way I've tried this so far is by giving an id to each <td>.
ajax code
$.ajax({
type : 'POST',
url : 'search_fetch.php',
data : data,
cache: false,
success : function(response)
{
result = jQuery.parseJSON(response);
$("#list_p_id").append(result.tb_personal_id);
$("#list_name").append(result.tb_name);
$("#list_status").append(result.tb_status);
$("#list_date").append(result.tb_entry_date);
}
});
How can I populate the table with all available results?
Also in case if helps, I am open to not use an array. I just don't know another way of how to send the results of a query to an ajax response.
In your while loop, you need to push each row of results onto your array in a way that doesn't overwrite the entire array each time.
For example:
while($row = mysqli_fetch_array($res))
{
array_push($data, array(
'tb_record_id' => $row['record_id'],
'tb_personal_id' => $row['personal_id'],
'tb_name' => $row['name'],
'tb_status' => $row['status'],
'tb_entry_date' => $row['entry_date'],
)
);
}
When you do this, keep in mind that $data is now an array of arrays, and you will need to access the items accordingly in your ajax.
ADDITIONAL INFORMATION TO ANSWER YOUR QUESTION:
I didn't realize you also need information about how to display the resulting data in your table...
You are going to need to use some kind of dynamic code to product your HTML in order to assign each table cell with a unique id.
When you have done that, you will need to use a loop in your ajax code so you can assign the resulting data to each table cell and display it.
Currently your loop will just overwrite the data into the existing elements over and over, meaning you only get one row of information.

How do I iterate over the results in a MySQLi result set?

I want to loop through the result set of the following query:
select uid from userbase
I am currently employing the following loop, but I can get only the first value.
$i = 0;
$output = mysqli_query($mysqli, "select uid from userbase");
while ($row = $output->fetch_array()) {
$deviceToken = $row[$i];
echo $deviceToken;
$i++;
}
What might be the problem? Is it fetch_array()?
You will notice while researching the PHP manual at https://php.net/manual/en/mysqli-result.fetch-array.php that fetch_array() has the default behavior of generating a result set that contains both indexed and associative keyed elements (MYSQLI_BOTH).
You could use either MYSQLI_ASSOC ...
while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
echo $row['uid'];
}
or MYSQLI_NUM...
while ($row = $output->fetch_array(MYSQLI_NUM)) {
echo $row[0];
}
That said, there is actually an easier, more brief, and more efficient way because MySQLi's query() can be used as an iterable object. The step of calling fetch_array() on every iterated row can be completely omitted. You can write your $output into a foreach() and away you go (refer to column values by the associative key).
foreach ($output as $row) {
echo $row['uid'];
}
I do recommend that you use all "object oriented" syntax rather than procedural or a mix of styles. "Object oriented" syntax is more brief and in my opinion it is easier to read.
Finally, the way that your code is constructed, $i starts at 0 and increments with every row. However, your result set (with both styles of keys) will look something like this...
[
0 => [0 => 1, 'uid' => 1],
1 => [0 => 2, 'uid' => 2],
2 => [0 => 3, 'uid' => 3]...
]
Your first iteration works because $output[0][0] (aka $row[0]) exists.
Your second iteration doesn't work because $output[1][1] (aka $row[1]) doesn't exist.
Nor does the third iteration with $output[2][2] (aka $row[2]) doesn't exist. And so on.You see, the iteration was truly the part that fouled up your script.
You need to define a array and store your data into array inside loop .
Use MYSQLI_ASSOC no need for incremented value
$deviceToken=array();
while ($row = $output->fetch_array(MYSQLI_ASSOC)) {
$deviceToken[] = $row['uid'];
}
print_r($deviceToken);
for($i=0;$i<=count($deviceToken);$i++){
echo $deviceToken[$i];
}

$row['column'] in PHP

Hello guys I have seen a code with $row['columnname'].The code is
$myQuery = "SELECT * FROM information_schema.columns WHERE table_name = '$tabname'";
$re = mysql_query($myQuery);
while($row = mysql_fetch_array ($re)){
if(!empty ($row)){
$col_name = $row['COLUMN_NAME'];
$myQuery = "SELECT ".$col_name." FROM ".$tabname." WHERE sampleid='".$sid."'";
echo "<br>".$myQuery;
$reqq = mysql_query($myQuery);
$roww = mysql_fetch_array($reqq);
echo "<br>".$roww[$col_name];
}
}
My question is what is the use of $row[] in php?
Is it used to embed the column value like $row['columnname'] or just adding a variable like $row[$anyvariable].
That is called bracket notation. $row is an array, which has properties. In this case, it has named properties, so it is an associative array. An associate array has key/value pairs. It looks like this:
$myArray = [
'key' => 'value'
];
To echo the value of the property above, you would use echo $myArray['key'];
In the specific code you included, the property name is "COLUMN_NAME" and it has a value. The code assigns that value to the variable $col_name.
Here's another sample usage to help clarify all of this:
$people = [
'Susan' => [
'Age' => 24,
'Phone' => '555-123-4567'
],
'Jack' => [
'Age' => 27,
'Phone' => '555-9876-5432'
]
];
echo $people['Jack']['Age']; // 27
while($row = mysql_fetch_array ($re)){
This statement loops over all the rows returned in your result set $re and while looping, on every iteration you will get the current row as an array in your variable named $row, this name can be anything, it doesn't have to be $row necessarily.
Then
$col_name = $row['COLUMN_NAME'];
Is just reading $row as an array and picking up the value for the key COLUMN_NAME. This will be one of the columns that were returned by your query for each row of the result set. This also can be any name depending upon your query.
it is from mysql_fetch_array
it returns result array if your query/result was found, if not just FALSE instead
Like it says on the PHP site :
mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or both
It's not variables that would go inside the $row[] , it's the column name that you have called in your SELECT query .
In your case, you have a SELECT query to return all the columns of a table. 'COLUMN_NAME' is in fact really the name of a column in the table of information_schema.column
mysql_fetch_array returns an array,
$row = [
'column_name' => 'column_value'
]
so the statement
$row = mysql_fetch_array ($re))
will fetches the column names from information_schema.columns that will be stored into $col_name.
$col_name = $row['COLUMN_NAME'];
for more read mysql_fetch_array

Fetch Value in reverse order using while loop

I have a code which retrieves the values from data base.but i want to fetch this values in reverse order.See this example
While($row=mysql_fetch_assoc($rs)){
echo $row['id']."<br>";//gives 1 and 2 and so on
echo $row['val']."<br>";// gives abc and def and so on
}
But i want
2
def
1
abc
How could i do this .i don't wanna use the Query for this like use of ORDER BY.so can i control this at PHP End??
while($row = mysql_fetch_array($rs)){
$data[] = $row;
}
$data = array_reverse($data,true);
while($data){
}
Haven't tested it though
I tested it in this site and it works. Here's the snippet I used:
$data = array(1 => array("foo" => "bar"), 2 => true);
$data = array_reverse($data,true);
print_r($data);
Edit:
Using your edited answer, I got this:
$data = array(1 => array(1, "abc"), 2 => array(2, "def"));
$data = array_reverse($data,true);
foreach($data as $d){
echo "id>".$d[0]." | val>".$d[1]."<br />";
}
Store your data in an array (in your while-loop). After that, you can use array_reverse to reverse item order.
You can also use a cursor that iterates through your result set -moving backwards and forwards - using something like PDO - and probably similar variations for each other type of connection:
cursor_orientation
For a PDOStatement object representing a scrollable cursor, this value determines which row will be returned to the caller. This value must be one of the PDO::FETCH_ORI_* constants, defaulting to PDO::FETCH_ORI_NEXT. To request a scrollable cursor for your PDOStatement object, you must set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you prepare the SQL statement with PDO::prepare().
But using an array_reverse might be simpler. Having said that, ordering the data in the query would be simpler again (and probably much more efficient).
$result = $mysqli->query($query);
for($i = $result->num_rows - 1; $i>0; $i--){
$result->field_seek($i);
$finfo = $result->fetch_field();
echo $finfo->id;
echo $finfo->val;
}

Two dimensional associative array in PHP

In my code I'm getting data (three columns) from a sql db and I want to store the rows in an associative PHP array. The array must be multi-dimensional because I want to use the row id from the database as a key so that i can fetch values like this:
$products["f84jjg"]["name"]
$products["245"]["code"]
I've tried using the following code but it doesn't work:
while ($row = mysql_fetch_row($sqlresult))
{
$products = array($row[0] => array(
name => $row[1],
code => $row[2]
)
);
}
Also, how should I reference the key if it is taken from a variable? What I want to do is:
$productName = $products[$thisProd]["name"];
Will this work?
This should do it, assuming row[0]'s contents is a unique identifier (else you could override a row):
while($row = mysql_fetch_row($sqlresult)) {
$products[$row[0]] = array(
'name' => $row[1],
'code' => $row[2]
);
}
You need to put quotes around the array keys, and you were creating an array of array of arrays.
Also note you could use mysql_fetch_assoc instead of mysql_fetch_row, which would give you the array keys as the column names, which would make this much easier/cleaner:
while($row = mysql_fetch_assoc($sqlresult)) {
$products[$row['myidcolumn']] = $row;
}
After you do this, the code you described would work.

Categories