retrieving data from a specific column in php/MySql - php

I'm using WordPress with XAMPP. I'm trying to fetch the post title from a column called post_title from a table called ltport_posts by using mysqli_fetch_row() function. The connection with the database is working just fine. However, post titles don't seem to be written in the news ticker. Now I know that $row variable is an enumerated array, so we should write the offset number to access the column. It should be noted that the while loop is working since I have four rows in the ltport_posts and four <div>'s are generated (browser's inspect element is showing me that). But the whole tag is empty:
<div class="ticker-wrap">
<div class="ticker">
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
<div class="ticker__item"> </div>
</div>
</div>
Here's the php/HTML code:
<div class="ticker">
<?php $query="SELECT post_title from ltport_posts";
if($result=mysqli_query($conn,$query))
{
while($row=mysqli_fetch_row($result))
{?>
<div class="ticker__item"><?php printf("%s", $row[5]); ?> </div>
<?php }
mysqli_free_result($result);
}
mysqli_close($conn);?>
</div>

mysqli_fetch_row
mysqli_result::fetch_row -- mysqli_fetch_row — Get a result row as an
enumerated array
Your query is
$query="SELECT post_title from ltport_posts";
You just fetch one column from your query. So you will get only $row[0] .It's indexing start from 0
while($row=mysqli_fetch_row($result))
{?>
<div class="ticker__item"><?php printf("%s", $row[0]); ?> </div>
<?php }
For fetching multiple column
$query = "SELECT column1, column2,column3,column4 FROM City ORDER by ID DESC";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
printf ("%s (%s)\n", $row[0], $row[1],$row[3], $row[4]);
}
}

You can do the following:
// Prepare the query
$stmt = "select column FROM table";
// Execute it...
$result = mysqli_query($stmt);
// Fetch Results
$row = mysqli_fetch_assoc($result);
// Output single column
echo $row['column'];
And of course you can loop it through as well with multiple results. mysqli_fetch_assoc will return an array where the keys are the column names.

Related

Export MySQL table to CSV via PHP by checkbox selection

I need to display a list of results form a survey on a PHP page then export them to a CSV file. The list also acts as a summary that can be clicked thorugh to the full result.
I have all that sorted but now I need to have the CSV export by a check bx selection so that we dont need to download the entire databse each time just the ones we need.
My code so far below.
<div class="resultsList">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type=\"checkbox\" name=\"xport\" value=\"export\"><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query1 = mysql_query("select * from results where survey_id=$id", $connection);
while ($row1 = mysql_fetch_array($query1)) {
?>
<?php
}
}
?>
<?php
mysql_close($connection); // Closing Connection with Server
?>
And the downloadcsv.php
<?php
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
$query = "SELECT * FROM results";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
Any help with this would be great, cheers
Updated with a screenshot of what I am trying to achieve
The initial result set needs to be wrapped in a form which POST to the next page.
The Checkbox must send an array of ids to the export script.
<input type='checkbox' name='xport[]' value='ID_OF_THE_ROW_HERE'>
The [ ] after xport means that $_POST['xport'] will be an array of values.
The export page can collapse that array of ids into a comma separated string and to be used the query:
SELECT * FROM results WHERE id IN (4,7,11,30)
<form method="POST" action="downloadcsv.php">
<h1>PEEM Results List</h1>
<a class="exportCSV" href="https://domain.com/downloadcsv.php">Export to CSV</a>
<!-- Export CSV button -->
<h3 class="resultsbydate">All results by date</h3>
<div class="resultsListHeader">
<div class="clientidTab">Agency</div>
<div class="clientidTab">Family ID</div>
<div class="clientidName">Name</div>
<div class="clientidTab">Date</div>
<div class="clientidTab"></div>
</div>
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) {
echo "<div><input type='checkbox' name='xport[]' value='{$row['client_id']}'><span>{$row['client_id']}</span> <span>{$row['family_id']}</span> <span>{$row['firstname']} {$row['lastname']}</span> <span>".date("d F Y", strtotime($row['peemdate']))."</span>";
echo "<span><a class=\"parents-button\" href=\"peem-parent-repsonses.php?id={$row['survey_id']}\"><strong>Parent’s Review</strong></a></span>";
echo "<span><strong>View Results</strong></span>";
echo "</div>";
}
?>
</div>
</form>
Change $row['client_id'] to the correct value
Then in the export script:
<?php
/*
Expecting $_POST['xport'] array of row ids
*/
if( !isset($_POST['xport']) OR !is_array($_POST['xport']) ) {
exit('No rows selected for export');
}
$conn = mysql_connect("localhost","username","password");
mysql_select_db("databasename",$conn);
$filename = "peem_results.csv";
$fp = fopen('php://output', 'w');
$query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='realwell_peemfinal' AND TABLE_NAME='results'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$header[] = $row[0];
}
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
fputcsv($fp, $header);
//Cast all ids to integer
$ids = $_POST['xport'];
array_walk($ids, function(&$value, $key) {
$value = (int)$value;
});
$ids = implode(', ', $ids);
$query = "SELECT * FROM results WHERE id IN ($ids)";
$result = mysql_query($query);
while($row = mysql_fetch_row($result)) {
fputcsv($fp, $row);
}
exit;
?>
So if I'm getting this correctly, you just need to be able to check checkboxes to select the databses ($rows) you want to insert into the csv file....
Every checkbox that you checked will be in the $_POST variable, so:
1st you make an array with all the names of checkbox options (databases), for example
$all_db = ['database1', 'database2', 'database3'];
2nd you loop through each of the values in $all_db and check if they exist in the $_POST array, if they do, then you can export the row
foreach( $all_db as $db_check ) {
if ( array_key_exists( $db_check, $_POST ) {
// EXPORT TO CSV
}
}
Don't forget ! This means the "name" attribute of the checkbox should be the name of the database.
If you don't want to have a static list of databases (i.e. there is a possibillity of them having different names in the future / there will be moreor maybe less etc then let me know i can edit my answer if needed :) )
( If you use the $_GET variable, then you can do the same thing just change $_POST to $_GET)
Know though that $_GET comes over as a bit amateuristic for the enduser if he gets a thousand variables in his URL,
$_POST is often a better alternative since it is hidden and cleaner for the enduser...
EDIT: UPDATING ANSWER (SEE COMMENT)
So basically you need people to be able to choose what rows they export from you dB...
First of all this means we need a unique ID for each row,
This can either be a column used solely for that (i.e. ID column with auto increment and unique attribute)
Or this can be a column you already have, just make sure it's a unique column so we don't get dupliate values (you'll see why below)
Then we give the value of this unique ID column to the checkbox's "name" attribute, and using jquery / php we append / prepend a static string...
For example, using your family ID:
"rownumber_" + $family_ID
This gets us (again using your example) :
$_POST[] = ['rownumber_123456' => 1, 'rownumber_0000000' => 1, .....]
So then in your PHP file you just do the following to add the correct lines to your CSV:
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['your_row_id'], $_POST) {
fputcsv($fp, $row);
}
}
-- Again using your example with family_ID : --
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
EDIT: Updating answer for comment no.2
So little sidenote if you are going to loop through html using php
(i.e. loop trhough db rows and print them out in an orderly fashion)
Then you propably want to use the ":" variants of the loops,
While() :
for() :
foreach() :
if () :
.....
These variants allow yu to close the php tag after the ":" and whataver html / css / php / jquery you put in the condition / loop will be executed like normal...
For example you can do :
<ul>
<?php foreach ($row as $columnkey => $columnvalue): ?>
<img src="whateveryouwant"?>
<li class="<?php echo $columnkey;?>">This is my value: <?php echo $columnvalue; ?></li>
<?php endforeach; ?>
</ul>
When you do it this way it's much cleaner and you won't have any problems using double quatation signs and all that stuff :)
So using that method here is how your displayed list would look like in code:
<div class="entriesListMain">
<?php
$connection = mysql_connect("localhost", "username", "password"); // Establishing Connection with Server
$db = mysql_select_db("database_name", $connection); // Selecting Database
//MySQL Query to read data
$query = mysql_query("select * from results ORDER BY peemdate DESC", $connection);
while ($row = mysql_fetch_array($query)) :
?>
<div>
<input type="checkbox" name="<?php echo $row['family_id']; ?>" value="export">
<span><?php echo $row['client_id']; ?></span>
<span><?php echo $row['family_id']; ?></span>
<span><?php echo $row['firstname'] . " " . $row['lastname']; ?></span>
<span><?php echo date("d F Y",strtotime($row['peemdate']); ?></span>;
<span>
<a class="parents-button" href="peem-parent-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>Parent’s Review</strong>
</a>
</span>
<span>
<a href="peem-repsonses.php?id=<?php echo $row['survey_id']; ?>">
<strong>View Results</strong>
</a>
</span>
</div>
<?php endwhile; ?>
</div>
Like this the checkbox will get the name of the family ID, and so in your csv.php you can use this code :
while($row = mysql_fetch_row($result)) {
if ( array_key_exists($row['family_ID'], $_POST) {
fputcsv($fp, $row);
}
}
Since now it will check for each row wether the family ID of the SQL row is posted as a wanted row in the $_POST variable (checkbooxes) and if not it won't export the row into the csv file ! :)
So there you go ^^
EDIT 3: Troubleshooting
So there are a couple of things that you do in this function,
the form,
Do the checkboxes in your html form have the family_ID in their name attribute ?
(i.e. <input type="checkbox" name="<?php echo $row['family_id']; ?>".... check if the name attribute is really filled )
you post stuff from a form, (your checkboxes and stuff)so let's see what actually gets posted,
die(print_r($_POST)); - This means you want php to die after this line (stop working at all), then print out a variable as is (sort of xml format you'll see)
So then you will get a whole bunch of information, if you want to see this information in a nicely formated way, just right click inspect element on it :)
Then see how your checkboxes are coming out of the $_POST variable,
(they should have the family_ID as a key and a value of 1)
If that's all ok, then check your row['family_ID'] variable see if the family_ID is filled correctly, do the same with your whole $row variable, in fact check every variable you use in csv.php and then check why the key does not exist in the array you are searching for :)
Also dont forget to check that you filled the array_key_exists( has a key FIRST and an array[] LAST )
I can't help you directly with this , since this will propably be a faulty variable or a mistake in your form so try to find this yourself, if still nothing , post these variables values:
$_POST
$row
and the full HTML of your form

How to display 10 records per page and then how to use pagination?

One record
10 records loop
I have trouble with displaying properly records, end after that i need to use pagination.
v_news.php
<div class="news">
<a href="index.php?ogloszenie='<?php $row['id_article']; ?>'">
<div class="newstitle">
<?php echo $row['title'];?>
</div>
<div class="newsauthor">
<?php echo $row['username'];?>
</div>
<div class="newscomment">
comments: 56
</div>
<div class="newsdate">
<?php echo $row['timestamp'];?>
</div>
</a>
</div>
m_news.php
<?php
if(!isset($_SESSION['id'])){
header("Location: index.php");
exit();
}else{
$result = $Database->query("SELECT * FROM article LIMIT 0, 10");
if($result->num_rows != 0){
$rows = $result->fetch_assoc();
foreach ($rows as $row){
include("views/v_news.php");
}
}else{
echo "No results";
}
}
With foreach loop i have an error illegal string offset with $row['']. I don't know what to do with this.
First try to fix your 2nd line of code in v_news.php.
You forgot to use "echo".
<a href="index.php?ogloszenie='<?php $row['id_article']; ?>'">
change to:
<a href="index.php?ogloszenie='<?php echo $row['id_article']; ?>'">
fetch_assoc() fetches one row, not all.
You can use a while loop which will end once fetch_assoc() stops returning new rows.
while($row = $result->fetch_assoc()){
include("views/v_news.php");
}
For pagination, you only need to change LIMIT parameters
i.e. LIMIT 10,10 would be the second page data (10 total rows starting with row 10).
Also as bobiczeq pointed out you should ensure the echo statement appears in <?php $row['id_article']; ?> otherwise this is only empty.
I found correct answer.
$rows = mysqli_fetch_all($result, MYSQLI_BOTH);
Now it's working correctly.

Code is not displaying first result

About this code:
<?php
$result = mysqli_query($connect,"SELECT subcategories.subcat_name, subsubcategories.subsubcat_name FROM subcategories INNER JOIN subsubcategories ON subcategories.subcat_ID=subsubcategories.subcat_ID WHERE subsubcategories.subcat_ID = 1");
$subcat_name = mysqli_fetch_array($result);
?>
<div class="grid_5 alpha omega" id="titlescontent"><p class="titlebar"><?php echo $subcat_name['subcat_name'];?></p></div>
<div class="clear"></div>
<div class="grid_5 alpha omega" id="content"><ul class="subcat">
<?php
while ($row=mysqli_fetch_array($result)){
?><li><?php echo $row['subsubcat_name'];?></li><?php
}
?>
</ul></div>
<div class="clear"></div>
For some reason it starts displaying the subsubcat_name from the 2nd result and not the first one which I also want to be displayed. Any idea how come and what I need to change in this code?
Actually, I see you need that first one for the title? In that case, try this alternate approach:
Replace your while loop with:
$row = $subcat_name;
do {
echo "<li>".$row['subsubcat_name']."</li>";
} while($row = mysqli_fetch_array($result));
What does this change? It basically means the loop body will run for your initial row, then for the rest.
you have extra mysqli_fetch_array call

Multiple rows from db

I'm trying to echo out multiple rows from a sql database, but I get the error Warning. Illegal string offset 'Date' In....
$channel_check = mysql_query("SELECT content, Date FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC;");
$numrows_cc = mysql_num_rows($channel_check);
if ($numrows_cc == 0) {
echo '';
// They don't have any channels so they need to create one?><h4> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspYou haven't posted anything yet. You can post what's going on in your life, how you're feeling, or anything else that matters to you.</h4>
<?php
}
else
{
?>
<div id="recentc">
</div>
<?php
echo"<h2 id='lp'> Latest Posts</h2>";
while($row = mysql_fetch_array($channel_check)) {
$channel_name = $row['content']['Date'];
?>
<div style="margin-top:60px;">
<hr style="margin-right:340px;width:600px; opacity:0;">
<?php echo "<div id='rpc'><h6> $channel_name</h6></div>";?>
</div>
<?php
}
}
?>
DATE is a datatype in SQL, you need to escape it with back ticks
SELECT content, `Date` FROM wgo WHERE Posted_By='$user' ORDER by `id` DESC
Also, you're accessing your row incorrectly. Rows are typically represented by a uni-dimensional array, so $row['content'] and $row['Date']
$row is 1-dimensional array with 2 fields: content and Date.
Try,
while ($row = mysql_fetch_array($channel_check)) {
print_r($row);
//$channel_name = $row['content']['Date'];

PHP WHILE loop mysteriously not producing any output

Code first, explanation after:
$result = mysql_query("INSERT INTO messages (...) VALUES (...)") or die(mysql_error());
$rowID = mysql_insert_id();
if($result) {
$query = mysql_query("
SELECT ... LIMIT 1");
while ($row = mysql_fetch_array($query)) :
$message_id = stripslashes($row["m_id"]);
$message_postedby = stripslashes($row["u_name"]);
$message_text = stripslashes($row["m_text"]);
$date = date('F d, Y \a\t g:iA', strtotime($row["m_date"]));
?>
<div class="wall_message" id="<?= $message_id ?>">
<div class="author"><?= $message_postedby ?></div>
<div class="message"><?= $message_text ?></div>
<div class="date"><?= $date ?></div>
</div>
<?php
endwhile;
} ?>
What I'm doing:
Insert new row into database
Store ID of inserted row in variable $rowID
If insert was successful, query the database to retrieve that row along with any other related information from other tables
Store values from the row in variables
Print the divs containing that info
All of this is being called from a jQuery function, so I'm expecting that all of my HTML will be returned, but nothing is being returned inside the WHILE loop. I can echo text before and after it, and I see it just fine, but nothing inside the loop will print, and I just can't see my mistake. Not getting any errors either.
Thanks.
mysql_fetch_array() doesn't take a query, it takes a resource (result).
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
Also worth nothing that if you are only accessing the associative keys from the result, you should use mysql_fetch_assoc() instead.

Categories