I want to display data from my database but I have the following problem. I would like to display only the first 120 characters of the row 'text'. I know I can do this with the substr function.
I tried to implement substrin my code, but no text is shown when I reload the webpage ...
The whole code:
(connect to database)
$sql = "SELECT * FROM `table-example`";
// perform the query and store the result
$result = $conn->query($sql);
$text= $row['text'];
// if the $result contains at least one row
if ($result->num_rows > 0) {
// output data of each row from $result
while($row = mysqli_fetch_array($result))
{?>
<div id="preview">
<div class="title">
<?php echo $row['title'];?>
</div>
<div class="subtitle">
<?php echo substr($text, 0, 120);?>
</div>
</div>
<?php
}// end while
}// end if
else {
echo '0 results';
}
?>
(close connection)
Can someone please explain to me how to solve this?
The solution is to place $text = $row['text'] within the while loop.
Since before that, you don't declare $row to anything, therefore $text doesn't get set. Because $text isn't set, the substr method will shorten nothing AKA the echo returns nothing.
Related
I need to put a space between two words for a few iterations of my SQL query but I don't want it to happen for every use.
I tried putting margins with CSS, it didn't work. Here is a example of the code i'm working with:
<div class="CodeContainer">
<div class="row">
<?php
$query = "
SELECT
DISTINCT
CASE
WHEN code = '1' THEN 'TheOne'
WHEN code = '0' THEN 'Zero'
END
FROM
table
WHERE
code IN
(
'1',
'0'
);
";
$result = mysqli_query($db, $query);
// But do check if it returned results
if (mysqli_num_rows($result) == 0) {
die("$query returned 0 results, ask admin to check if Filters.php data is correct");
}
// Array all the codes the query returned
$codes = mysqli_fetch_all($result, MYSQLI_NUM);
?>
<div class="column">
<!-- Start looping through the $codes array -->
<?php
//Count each iteration of $code
$codecount = 0;
foreach($codes as $code):
// New column for every 1 iterations
if ($codecount == 1) {
echo '</div>';
echo '<div class="column">';
}
$codecount++;
?>
<label class="CodeCheckbox">
<input type="checkbox" name="Code" value="<?php echo $code[0]; ?>" checked>
<div class="CodeLabel"><?php echo $code[0]; ?><!-- This is where I want a specific iteration to have a space --></div>
</label>
<?php endforeach; ?>
</div>
</div>
</div>
I expect there to be a space between 'The' and 'One' only when $code[0] = TheOne between <div class="CodeLabel"> but no other iterations of $code[0]
Since you're wanting different behavior for one specific condition, it seems like you could just check for that condition on output and modify the text if the condition is met rather than trying to do it in the query.
<?php echo $code[0] == 'TheOne' ? 'The One' : $code[0]; ?>
I may have misunderstood what you meant by "I don't want it to happen for every use", though. I assumed you meant other uses of the same query.
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.
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 am new to PHP , I hope someone can help me. I have a table which contains "id" , "img" , "link" and "desc" in mysql database . I want it to echo all out into something like this :
<div id="featured">
<a target='_blank' href='link'><img src='image link1' title='description'/></a>
<a target='_blank' href='link'><img src='image link2' title='description'/></a>
<a target='_blank' href='link'><img src='image link3' title='description'/></a>
<a target='_blank' href='link'><img src='image link4' title='description'/></a>
</div>
<div id="cap">
<span class='desc' id='idnumber'>Description1</span>
<span class='desc' id='idnumber'>Description2</span>
<span class='desc' id='idnumber'>Description3</span>
<span class='desc' id='idnumber'>Description4</span>
</div>
PHP CODE:
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Can WHILE being used twice or i am wrong? when i run this code , the second while loop is not working , the spans are not showing at all.
Please help.
The first loop consumes all data from mysql already, so there is nothing left in the second loop. You can store the rows data in the meanwhile however and then re-use that store.
<div id="featured">
<?php
$rows = array();
while($row = mysql_fetch_array( $query )){
$rows[] = $row;
echo "<a target='_blank' href='$row[link]'><img src='$row[img]' title='$row[desc]'/></a>";
}
?>
</div>
<div id="cap">
<?php
foreach($rows as $row){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
closedb();
?>
</div>
Use this before your second while loop
mysql_data_seek($query,0);
The DB reference ($query) acts as a pointer to the next unread record; when you call mysql_fetch_array(), it gets the record that is being pointed to, and moves the pointer to the next position.
Therefore, after looping through them all, the pointer will be pointing at the end of the record set, hence it returns false when you ask for the next record. Finishing the loop does not do anything else to the pointer; it remains pointing to the end of the record set.
So what you need to do is reset the pointer to the start of the data set before you can loop through it a second time.
The function to do this is mysql_data_seek();
Therefore you'd need the following line of code immediatly before your second loop:
mysql_data_seek($query, 0);
Hope that helps.
Fromt the docs for mysql_fetch_array
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
The internal data point is still at the end when you try to use your second while loop. You have done nothing to reset it.
You can move it back to the start with mysql_data_seek
You can use while twice, but see what it does:
It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.
Once mysql_fetch_array has no more rows to fetch, it will return false on every subsequent call - so your first while loop will stop looping, as the expression mysql_fetch_array( $query ) is false; and since it's the same expression in the second while, that loop will never execute (as the expression evaluates to false).
What to do: If you want to loop over the results multiple times, I'd suggest to store the result rows into an array first, then loop over them. Simplified example:
$results = Array();
while ($row = mysql_fetch_rows($query)) {
$results[] = $row;
}
foreach ($results as $row) {
echo $row['something'];
}
mysql_fetch_array will be empty because you have already fetched all of the rows from the database. You will need to reset the pointer using mysql_data_seek.
<?php
mysql_data_seek( $query, 0 );
while($row = mysql_fetch_array( $query )){
echo "<span class='desc' id='$row[id]'>$row[desc]</span>";
}
... rest of code
With mysql_fetch_array() you are going through the results step by step, till you are at the end. Or as the PHP docs say:
Returns an array that corresponds to
the fetched row and moves the internal
data pointer ahead.
This means, you need to start from new. So, use this before your second while:
mysql_data_seek($query,0);
try this
<?php
require_once "./dbconfig.php";
opendb();
$sql = "SELECT * FROM images ORDER BY id DESC";
$query = querydb($sql);
$query2 = querydb($sql);
?>
<div id="featured">
<?php
while($row = mysql_fetch_array( $query )){
echo "<a target='_blank' href='$row[link]'><img src='$row[img]'
title='$row[desc]'/> </a>";
}
?>
</div>
<div id="cap">
<?php
while($row2 = mysql_fetch_array( $query2 )){
echo "<span class='desc' id='$row2[id]'>$row2[desc]</span>";
}
closedb();
?>
$str_res1 ='';
$str_res2 ='';
while($row = mysql_fetch_array( $query )){
$str_res1 .= " a target='_blank' href='$row[link]' img src='$row[img]' title='$row[desc]' a";
$str_res2 .= "span class='desc' id='$row[id]'> $row[desc] span>";
}
sorry i couldn't complete html tags in my answer as it disappears from post if i write "<" or "/>"
by this you can take all values in php strings and you can echo it any where you want to .
$stuff = mysql_query("SELECT * FROM tbl");
while($s = mysql_fetch_array($stuff)){
//ur code
}
// add this line
mysql_data_seek( $stuff, 0 );
while($r = mysql_fetch_array($stuff)){
//ur code
}
mysql_data_seek($query, 0); is deprecated since php 5.5 and removed from php 7.0
use mysqli_data_seek($query, 0); instead
I have this php code, with which I am trying to generate a popup window that will contain the contents of a html file, however after adding in the script tags, no html is displayed. I tried echoing out $row2, but the word array is printed to the screen and nothing else.
<?php
session_start();
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
die("You should have a 'cmd' parameter in your URL");
$pk = $_GET["pk"];
$con = mysql_connect("localhost","root","geheim");
if(!$con)
{
die('Connection failed because of' .mysql_error());
}
mysql_select_db("ebay",$con);
if($cmd=="GetAuctionData")
{
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
$sql2="SELECT ARTICLE_DESC FROM Auctions WHERE ARTICLE_NO ='$pk'";
$htmlset = mysql_query($sql2);
$row2 = mysql_fetch_array($htmlset);
echo $row2;
echo '<script>
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write('.$row2["ARTICLE_DESC"].');
child1.document.close();
}
</script>';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
echo "<div id='leftlayer'>
<strong>Article Number</strong> ".$row['ARTICLE_NO']."
<p><strong>Article Name</strong></p> ".$row['ARTICLE_NAME']."
<p><strong>Subtitle</strong></p> ".$row['SUBTITLE']."
<p><strong>Username</strong></p> ".$row['USERNAME']."
<p><strong>Total Selling</strong></p> ".$row['QUANT_TOTAL']."
<p><strong>Total Sold</strong></p> ".$row['QUANT_SOLD']."
<p><strong>Category</strong></p> ".$row['CATEGORY']."
<p><strong>Highest Bidder</strong></p> ".$row['BEST_BIDDER_ID']."
</div>
<div class='leftlayer2'>
<strong>Current Bid</strong> ".$row['CURRENT_BID']."
<p><strong>Start Price</strong></p> ".$row['START_PRICE']."
<p><strong>Buyitnow Price</strong></p> ".$row['BUYITNOW_PRICE']."
<p><strong>Bid Count</strong></p> ".$row['BID_COUNT']."
<p><strong>Start Date</strong></p> ".$row['ACCESSSTARTS']."
<p><strong>End Date</strong></p> ".$row['ACCESSENDS']."
<p><strong>Original End</strong></p> ".$row['ACCESSORIGIN_END']."
<p><strong>Auction Type</strong></p> ".$row['AUCTION_TYPE']."
</div>
<div class='leftlayer2'>
<strong>Private Auction</strong></p> ".$row['PRIVATE_AUCTION']."
<p><strong>Paypal Accepted</strong></p> ".$row['PAYPAL_ACCEPT']."
<p><strong>Auction Watched</strong></p> ".$row['WATCH']."
<p><strong>Finished</strong></p> ".$row['FINISHED']."
<p><strong>Country</strong></p> ".$row['COUNTRYCODE']."
<p><strong>Location</strong></p> ".$row['LOCATION']."
<p><strong>Conditions</strong></p> ".$row['CONDITIONS']."
</div>
<div class='leftlayer2'>
<strong>Auction Revised</strong></p> ".$row['REVISED']."
<p><strong>Cancelled</strong></p> ".$row['PRE_TERMINATED']."
<p><strong>Shipping to</strong></p> ".$row['SHIPPING_TO']."
<p><strong>Fee Insertion</strong></p> ".$row['FEE_INSERTION']."
<p><strong>Fee Final</strong></p> ".$row['FEE_FINAL']."
<p><strong>Fee Listing</strong></p> ".$row['FEE_LISTING']."
<p><a href='#' onclick='makewindows(); return false;'>Click for full description </a></p>
</div>";
$lastImg = $row['PIC_URL'];
echo "<div id='rightlayer'>Picture Picture
<img src=".$lastImg.">
</div>";
}
}
mysql_close($con);
?>
edit: I have fixed the errors that Roborg pointed out, however the script will still not load and does not give a precise error.
i have updated the code above
As well as the missing </script>,
child1.document.write('.$row2["ARTICLE_DESC"].')
should be
child1.document.write(' . json_encode($row2["ARTICLE_DESC"]) . ');
The json_encode() function will take care of any quoting for you.
Edit:
<a href='#' onclick=makewindows()> should be <a href='#' onclick='makewindows(); return false;'> - You should have quotes there, and the return false will stop you getting taken to "#" when you click the link.
Also, from memory I'm not sure you can open about:blank and then write to it - I think it sees that as cross-domain scripting. You might be better off creating a minimal "blank.html" file on your server and using that.
You have to print_r an array, like print_r($row2);
In this line:
$row2 = mysql_fetch_array($htmlset);
You are setting $row2 to be an array representing an entire row of the result from your query. Even if the "row" is just one field, it's still an array. If you want to get just the value of the first field, you can use mysql_result.
The parameters are: resource $result , int $row [, mixed $field ] so an example of the usage would be:
// get the first field of the first row
$fieldVal = mysql_result($htmlset, 0);
// get the third field
$fieldVal = mysql_result($htmlset, 0, 2);
// get the first field of the 2nd row
$fieldVal = mysql_result($htmlset, 1);
Your <script> tag is never closed and your JavaScript instructions are not ended with semicolons. It might be the source of the problem.