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.
Related
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
I have a PHP function that returns a single row from a localhost MySQL table like so:
<?php
//include database connection process
require_once("includes/conn.inc.php");
//prepare statement
$stmt = $conn->prepare("Select * FROM races WHERE raceID = ?");
$id = 1;
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
?>
What I would like to do with this array is output the data from the individual fields in their own HTML <div> or <p> with a heading indicating what they mean in a separate div. I currently user the print_row method that outputs everything in one. All the data I want is there, but I'd like it separated out into name/value paragraphs or divs.
//what I currently have
<?php
print_r($row);
?>
Is there a way to do this?
Thanks in advance,
Mark
I didn't understand the question very well but I think I understand what you need.
Use while to iterate trough each row.
while($row = $resultDesc->fetch_assoc())
{
echo '<p><strong>Description:</strong></p> ';
echo '<p>'. $row['description'] . '</p>';
}
That's not the exact solution but atleast shows you the path.
You can use foreach
<?php foreach ($row as $key => $val): ?>
<p><strong><?php echo $key; ?>:</strong></p>
<p>
<?php
//output relevant attribute
//of query run on page load
echo $val;
?>
</p>
<?php endforeach; ?>
I'm wondering what is the appropriate syntax is to echo a row from MySQLi code in a block of HTML text. I'm working on a page that uses PHP code at the start to determine if a session is started and to post comments that user has posted, after pulling said comments from a MySQLi database. The interesting and confusing part is, I've accomplished what I'm trying to do in one HTML div, but I can't seem to get it to work in the next.
<?php
$page_title = "store";
require_once('connectvars.php');
require_once('startsession.php');
require_once('header.php');
// Connect to the DB
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Grab location data from the DB
// Grab post data
$query2 = "SELECT sp.post_id, sp.admin_id, sp.post, sp.date, sa.admin_id, s.store_name, s.store_city, s.store_state, s.store_zip,s.store_phone, s.store_email, s.store_address FROM store_posts sp, store_admin sa, stores s WHERE sp.admin_id='$admin_id' and sa.admin_id='$admin_id' and s.admin_id='$admin_id'ORDER BY date DESC";
$data = mysqli_query($dbc, $query2);
if (mysqli_num_rows($data) == 0) {
$blankwall = "Empty feed? '<a href=manage.php><u>Click here</u></a> to manage posts and communicate with your customers!";
}
?>
<body>
<div id="content">
<!-- BANNER & CONTENT-->
<h2>Recent Posts</h2>
<div id="store_wrap">
<div id="left_col">
<br />
<?php
**// Loop through posts and show them
if (mysqli_num_rows($data) == 0) {
echo $blankwall;
}
else {
while ($row = mysqli_fetch_array($data)) {
// Show the posts
echo '' . $row['post'] . ' | ';
echo date('M j, Y g:i A', strtotime($row['date']));
echo '<br /><hr />';
}**
}
?>
</div><!-- closes left_col -->
So all the above code is there to query the DB to grab the correct array and then show $row['posts'] in the HTML div below the PHP code, titled left_col. I am trying to do the exact same thing in the next div but instead of echoing $row['posts'], I want to echo rows such as $row['store_city'] to have the page display the store's location after pulling it out of the previously selected array. Here's my non-functioning code for that part:
<div id="right_col">
<div id="store_picture">
<img src="images/store.jpg" style="width:325px;"/>
</div><!-- closes picture --><br />
<div id="store_address">
<br /><br /><h2>Location Info</h2>
<?php
if (mysqli_num_rows($data) == 1) {
while ($row = mysqli_fetch_array($data)) {
echo '<p>' . $row['store_city']. '</p>';
}
}
mysqli_close($dbc);
?>
</div><!-- closes store_address -->
<div id="store_info">
<p></p>
</div><!-- closes store_info -->
</div><!-- closes right_col -->
<div class="clear"></div>
</div><!-- closes store_wrap -->
</div><!-- closes content -->
For whatever reason, the second time, when I try to echo data from that array, I just have empty space within that div. I don't get any errors. I just don't get...anything. Therefore, I think this is a syntax issue. I've tried exactly the same thing I did with the section where I echo $row['post'] and it isn't working.
The chief issue you're facing is that you make a second attempt at fetching rows from the $data MySQLi result resource object after already having fetched them once. This won't work as intended, as MySQL keeps an internal recordset pointer which advances every time mysqli_fetch_array() is called. So when the end of the first loop is reached, the pointer is at the end of the recordset and a subsequent call will return FALSE.
Therefore, your second loop gets nowhere because its first call to mysqli_fetch_array() returns FALSE, exiting the loop. You have two options.
The quickest fix is to just rewind the record pointer using mysqli_data_seek(). Called right before the second loop, it will set the pointer back to the first record, allowing you to fetch them all again.
if (mysqli_num_rows($data) == 1) {
// Rewind the record pointer back to the first record
mysqli_data_seek($data, 0);
while ($row = mysqli_fetch_array($data)) {
// note addition of htmlspecialchars() to escape the string for HTML!
echo '<p>' .htmlspecialchars($row['store_city']). '</p>';
}
}
Perhaps a better option if your recordset is small is to fetch all rows into an array once, then use that array with a foreach loop for both your subsequent output loops:
// To hold all rows
$rows = array();
// Do the query
$data = mysqli_query($dbc, $query2);
// (don't forget to check for errors)
if ($data) {
while ($row = mysqli_fetch_array($data)) {
// Append the row onto the $rows array
$rows[] = $row;
}
}
else{
// handle the error somehow...
}
Later, instead of using $data again, you will loop over $rows with a foreach loop.
// use count($rows)
if (count($rows) == 0) {
echo $blankwall;
}
else {
foreach ($rows as $row) {
// Show the posts
echo '' . $row['post'] . ' | ';
echo date('M j, Y g:i A', strtotime($row['date']));
echo '<br /><hr />';
}
}
...And do the same thing again for your second loop later in the code. It's recommended to use htmlspecialchars() on the string fields output from the query where appropriate.
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>                                                                                                             You 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'];
in my tableX some datas are there which looks like this
<h1>ghhhhhh!</h1>
http://twitter.com/USERNAME
<h1></h1>
http://3.bp.blogspot.com/_fqPQy3jcOwE/TJhikN8s5lI/AAAAAAAABL0/3Pbb3EAeo0k/s1600/Srishti+Rai1.html
<h1></h1>
http://4.bp.blogspot.com/_fqPQy3jcOwE/TJhiXGx1RII/AAAAAAAABLc/XNp_y51apks/s1600/anus7.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhh1ILX47I/AAAAAAAABKk/gX-OKEXtLFs/s1600/4r-2.html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhiHGgb-KI/AAAAAAAABK8/zEv_41YzMhY/s1600/19+(1).html
<h1></h1>
http://cyz.com/_fqPQy3jcOwE/TJhihkpZZKI/AAAAAAAABLs/zDnlZkerBd8/s1600/Pooja+Gurung.html
when i echo the same php code it gives correct output but when i am storing these details in mysql only one row is getting stored in mysql row.
my code is this
<?php
include('connect.php');
$idmg=$_POST["id"];
$res =mysql_query("select * from tablea");
$row = mysql_fetch_array($res);
if(sus== '0'){
$output=''.$row['content'].'';
echo $output;//this output gives the above result but when i store in db it stores first row
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
} ?>
Your insert is failing because you have unescaped data in $output. Take DCoder's advice above and use PDO or mysqli.
Is there a reason you have sql_fetch_array() and not mysql_fetch_array() ?
You also need to iterate through your results if you want more than one row.
<?php
include('connect.php');
$idmg =$_POST["id"];
$res =mysql_query("select * from tablea");
$row = sql_fetch_array($res)
if($sus== '0'){
$output=mysql_real_escape_string($row['content']);
echo $output;
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
}
?>
And as #DCoder said, you should be using prepared statements, the code you have now is vulnerable to SQL injection.
Your code some-what corrected:
<?php
include('connect.php');
$idmg=$_POST["id"];
$res = mysql_query("select * from tablea");
$row = mysql_fetch_array($res);
if($sus== '0'){ // what is sus? If variable.. should be $sus
$output = $row['content']; // .'' is literally nothing..
echo $output;
mysql_query ("INSERT INTO tablea (content) VALUES ('$output')");
}
?>
What I think you are trying to do:
<?php
include('connect.php');
$idmg = $_POST["id"]; // not actually used
$res = mysql_query('SELECT * FROM tablea');
while($row = mysql_fetch_array($res)) {
$output = $row['content'];
echo $output;
// do anything else you want.. in your case ?enter the data back in?
mysql_query("INSERT INTO tablea(content) VALUES('$output')");
}
?>
What you should be using:
<?php
$idmg = $_POST['id']; // <-- not actually used
$res = $mysqli_connection->query('SELECT * FROM tablea');
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$output = mysqli_connection->real_escape_string($row['content']);
echo $output;
// Do whatever else you like
$mysqli_connection->query("INSERT INTO tablea(content) VALUES('$output')");
}
$res->free();
$mysqli_connection->close();
?>