error outputting html with javascript - php

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.

Related

Insert into mysql using div codes and php

the below to functions contain the code to insert into the sql database but sadly the db is still unable to load it to the database.
if (isset($_POST['register'])){
if(registerNewUser($_POST['inv_amount_expected'],$_POST['uname'],$_POST['passwo rd'],$_POST['email'])){
echo "You can now log-in to your account.
<a href='./index.php'>Click here to login.</a>
";
}else {
echo "Registration failed! Please try again.";
show_registration_form();
}
} else {
// has not pressed the register button
show_registration_form();
}
function registerNewUser($inv_amount_expected,$uname,$password,$email)
{
$sql = sprintf("insert into borrow (inv_amount_expected,uname,password,email) value ('&inv_amount_expected','&uname','&password','&email')",
mysql_real_escape_string($username), mysql_real_escape_string(sha1($password . $seed))
, mysql_real_escape_string($email), mysql_real_escape_string($code));
if (mysql_query($sql))
{
$id = mysql_insert_id();
return true;
}
else
{
return false;
}
return false;
}
could you help me out in where i am going wrong since im unable to understand.
i'm still an amature in php so please help me out.
I am putting my ideas together and at the moment i have the following:
-a mysql database with 2 tables.
-the first table "downloads" contains 3 rows, each with a unique id that and each represent the type of file being downloaded. e.g. application or theme.
-the second table contains the information about each download, these fields are the models supported by the download, the title, a picture, a brief description and a download link. each download has a unique id.
Now what i am trying to do is insert the data into a set of divs, these divs are as follows:
<div class="dlcontainer">
<div class="dlitem">
<div class="dltitle"><php $row['title'] ?></div>";
<div class="dlimage"><php $row['image'] ?></div>";
<div class="dldescription"><php $row['description'] ?></div>";
<div class="dllink"><php $row['downlink'] ?></div>";
</div>
</div>
As you can see i have been trying to populate the divs with information called from the database and that was my first attempt.
I didn't feel like i was going about this with the right approach, so i ended up with this, which also does not seem to work:
<?php
$con = mysql_connect("test","test","test");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM `content` WHERE pid = '2' AND models = 'all' OR models = $chosen");
while($row = mysql_fetch_array($result))
{
echo "<div class=\\"dlcontainer\\">";
echo "<div class=\\"dlitem\\">";
echo "<div class=\\"dltitle\\">$row['title']</div>";
echo "<div class=\\"dlimage\\">$row['image']</div>";
echo "<div class=\\"dldescription\\">$row['description']</div>";
echo "<div class=\\"dllink\\">$row['downlink']</div>";
echo "</div>";
echo "</div>";
}
mysql_close($con);
?>
Once i get this initial download working, i can then set up a loop that will display all the contents that match belong to a specific "pid" and either match a "models" value of "all" or one that has been selected by the user.

How to echo a MySQLi row in escaped PHP code, inside an HTML block

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.

Limit characters of data to display on webpage with substr

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.

Outputting values from MySQL into a preformatted table

I am making a periodic table and am new to php. I have looked far and wide for information on how to accomplish this task, but I can't find anything. What I want to do is query my database and get values for things like atomic weight, name, element symbol, etc, and have them populate in my periodic table that I have constructed with html and css. However, I just don't know to run the "while" loop and have the data populate in the appropriate spaces. I understand how to create a table with the results, but I don't understand how to have results populate into an html structure that has already been created. Here is a part of my code. Again, I am very new to php, so any help would be greatly appreciated. I'm fairly certain this has a lot to do with where I'm placing my opening/closing php tags. Essentially, how do I get the loop to recognize the variables within the html? Do I close php tags and reopen?
Thank you tremendously.
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
//begin table structure where I would like to insert data//
<div id="hydrogen" class="element group1 period1">
<span class="number"> echo $row['atomicNumber']; </span><br>
<span class="symbol">H</span><br>
<span class="name"> echo $row['name']; </span><br>
<span class="molmass">1.007 94</span></div>
<div id="Helium" class="element group18 period1">
<span class="number">echo $row['atomicNumber'];</span><br>
<span class="symbol">He</span><br>
<span class="name"> echo $row['name']; </span><br>
<span class="molmass">4.002 602</span></div>
//...table continues...//
?>
You could go with two approaches, using PHP to echo the HTML or having PHP in the HTML.
PHP printing HTML
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
//begin table structure where I would like to insert data//
echo '<div id="hydrogen" class="element group1 period1">';
echo ' <span class="number">' . $row['atomicNumber'] . '</span><br>';
echo ' <span class="symbol">H</span><br>';
echo ' <span class="name">' . $row['name'] . '</span><br>';
echo ' <span class="molmass">1.007 94</span></div>';
}
HTML with PHP
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
?>
//begin table structure where I would like to insert data//
<div id="hydrogen" class="element group1 period1">';
<span class="number"><?php echo $row['atomicNumber']; ?></span><br>';
<span class="symbol">H</span><br>';
<span class="name"><?php echo $row['name']; ?></span><br>';
<span class="molmass">1.007 94</span></div>';
<?php
}
Well i am not sure about whether you are storing the molmass,symbol,group and period in the MySQL table, but you most probably are. Since i dont know what you named them, please replace molmass,atomicSymbol,atomic_group and atomic_period with your coloumn name.
You can use this code,
<?php
//query database (connection successful)//
$result=mysql_query("SELECT * FROM elementdata", $link);
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
// echo the first line, i.e the div
echo "<div id='{$row['name']}' class='element {$row['atomic_group']} {$row['atomic_period']}'>";
// Echo the atomic number, symbol, name and molmass
echo "<span class='number'>{$row['atomicNumber']}</span><br>";
echo "<span class='symbol'>{$row['atomicSymbol']}</span><br>";
echo "<span class='name'>{$row['name']}</span><br>";
echo "<span class='molmass'>{$row['molmass']}</span><br>";
echo "</div>";
}
?>
Explaination: The {} is required for us to insert the $row[''] syntax in a string, else it gives us trouble.
Rest we just loop over everything in the table, fetch what you named them and what group and period they belong to, create a div. Then we print each of their properties.
You need to step in and out of PHP
After :
//fetch results into array to loop through//
while($row = mysql_fetch_array($result)) {
If you want to output HTML, you must close PHP
?>
Now when you want to output some PHP variable inside a HTML tag :
<span class="number"><?php echo $row['atomicNumber']; ?></span><br>
Similar to the opening and closing tags in HTML, you enclose your PHP code within PHP tags.
Well, let's try one possible way:
<html>
<head>
</head>
<body>
<?php
open your db stuff
$query = " SELECT name,
symbol,
atomicnumber,
molmass,
otherstuff
FROM periodictabletable
WHERE index > 0 ";
$result = mysqli_query($cxn, $query) or die ("could not query database");
echo "<table>";
while ($row = mysqli_fetch_array($result))
{
echo "<tr><td>".$row['name']."</td><td>".$row['symbol']."</td><td>".$row['atomicnumber']."</td><td>".$row['molmass']."</td></tr>";
}
echo "</table>";
?>
</body>
</html>
Once you get this up and running, you can embed all kinds of formatting tags into the html, just make sure you only use single quotes for stuff like - class='numbercolor' .
But there are many ways to do this. You could make the table in html, then populate it with an ajax call - depends on what you want to do.
Have fun!

WHILE loops can't be used twice? PHP

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

Categories