How to display this php code when php script is executed.
I only want to display these syntax not the result of the syntax.
This is for a making tutorial web site.
//sample code
$con = mysql_connect ("localhost", "root", "") or die(mysql_error ());
$db = mysql_select_db ("arraydb") or die(mysql_error ());
$i=0;
$sql = 'SELECT * FROM user_info WHERE i_id=130';
$query = mysql_query($sql);
foreach($result = mysql_fetch_assoc($query) as $key => $value)
{
echo '<pre>['.$key.' - '.$value.']</pre>';
}
echo '<hr/>%%<br><br><br>';
p.s i tried to type code without php tags then
1.html tags are not display
2.text indenting format is not visible in result
Assuming your code is in "sample.php" you could add the following line at the begining of your file or somewhere before the first "echo":
highlight_file('sample.php');
Note that you will see this line as well in the code sample.
You can try this http://micmap.org/php-by-example/en/function/highlight_string to get an idea of what it produces.
Did you try something like this ?
<?php
highlight_file(__FILE__);
echo '<br>';
// begin sample code
$a = 1;
$b = 2;
echo $a + $b;
// end sample code, result displayed below
use enclosed tags
< pre >
< /pre >
Related
Im trying to set a php variable to a field and row of a database. I use:
$moped_select = "SELECT * FROM moped_details WHERE moped_ID='$_SESSION[moped_number]'";
$selected_moped = $db->query($moped_select);
if (($selected_moped->rowCount()) >= 1) {
foreach($selected_moped as $row){
$moped_rate = $row['rate'];
}
This doesn't set $moped_rate as the field and row, I have seen other people use this line before and it works. Whats even weirder is that I use a similar line to this to place data in a form. Which looked like this (keep in mind it is inside a foreach(x as $row) loop:
echo "<td>".$row['model']."</td>";
This echos out correctly so im kinda confused why Any suggestions would be appreciated <3.
Your code should as below
$db=new PDO('mysql:host=localhost','username','password');
$moped_select = "SELECT * FROM moped_details WHERE moped_ID=?";
$selected_moped = $db->prepare($moped_select);
$db->execute([$_SESSION["moped_numberf"]]);
if(($db>rowCount()) >= 1) {
while($row=$selectedmoped->fetch(PDO::FETCH_ASSOC){
$moped_rate = $row['rate'];
}
OK i have a php link which is made up of several variables
<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>
The whole code is really long as it has a lot of pagination, so i will just include the basic query and the loop part.
$query1 = "SELECT Distinct model_type from $tableName where manufacturer='$manufacturer' AND fuel='$fuel_type' LIMIT $start, $limit";
$result = mysql_query($query1);
And then the bottom part where i get and show the results.
$count = 0;
$max = 2;
while($row = mysql_fetch_array($result))
{
$model_type = $row['model_type'];
$count++;
echo '<td class="manu"><div align="center">'.'<a href=\year.php? manufacturer='.$manufacturer.'&fuel_type='.$fuel_type.'&model_type='.$model_type.'>'.$model_type.'</a>'.'</div></td>';
if($count >= $max){
//reset counter
$count = 0;
//end and restart
echo '</tr><tr>';
}
}
now this works fine except when i take the mode type variable from the database it shows as 1 series, however when it is passed in this link it only gets the 1 and doesn't pick up the series.
Thanks
try to pass it like:
'.urlencode($model_type).'
Try To access it on next page with urldecode($_REQUEST['$model_type'])
I am not shure but you probably have a missing encoding Problem.
try this:
'.$model_type.'
Its url_encoding the values so your url doesnt get broken by ',",spaces and so on.
additional Hint:
Enclose your URL with " or ' so you do not get problems at the end.
I've started making a Video script that loads the videos using MySql and I am using Mysqli.
However, There's 2 Rows that it should post, but it only post the second none, not the first one.
It loads the results using "Brand" so if there's 2 rows named "Test", it only loads the second one, but not the first one.
So, what is causing this? I've tried with 3 rows, and it did not include the first row.
Code
<?php
{ /* Global Data */
ini_set('display_errors', 0);
ini_set('error_reporting', -0);
$GetPath = $_GET['b'];
$SqlUser = "root";
$SqlPass = "**Private**";
$SqlHost = "localhost";
$SqlData = "heisteknikk";
}
{ /* Mysql Connect */
$Sql = new mysqli($SqlHost, $SqlUser, $SqlPass, $SqlData);
if ($Sql->connect_error) { die("Sorry, Could not connect (".$Sql->connect_errno.") ".$Sql->connect_error);}
}
{ /* Test */
$Brand = $Sql->real_escape_string($GetPath);
$SqlData = "SELECT * FROM videos WHERE Brand = '".$Brand."'";
$SqlQuery = $Sql->query($SqlData);
if (!$SqlQuery) {
echo $Sql->error;
}
if ($SqlQuery->num_rows == 0) {
die("Nothing was found");
}
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
echo "
<tr><td>".$Heis['Brand']."</td><td>".$Heis['Name']."</td><td>".$Heis['Location']."
";
}
echo "</table>";
$Sql->close();
}
?>
This line causes the bug:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
With this line you effectively throw out the first row of the result set, as you don't process $Data at all in the code below. Just remove it, and your script should work fine (I assume that closing </td></tr> sequence was lost when pasting the code, am I right?)
Comment out (or better yet, remove) this line:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
It is grabbing the first row...then you aren't doing anything with $Data and then grabbing the second (and consecutive rows) for display in your while loop. Commenting out that line above will make your loop grab and display them starting at the first one.
In your code
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
you're fetching a row (with fetch_array), throwing it away and then fetching another row (with fetch_assoc). That's probably why you're only seeing one row instead of two
I am trying to include a file which is scraping all my data from varrious websites, however its not working. Heres my code.
firstly, the scraping php file. named scrapedata.php
<?php
//Include the Simple HTML DOM to use its functions, used by other following scripts.
//navigate to the content of variable html and save it in price data variable
//get the whole html of the webpage into variable html
include 'simple_html_dom.php';
$html = file_get_html('http://www.play.com/Electronics/Electronics/4-/16230382/New-Apple-iPod-Touch-8GB-4th-Gen/Product.html?');
$price_data = $html->find('h6[id=bodycontent_0_middlecontent_1_ctl00_ctl00_product_ctl00__overview_ctl00__dataControl__price__headerSix',0)->plaintext;
//Amazon.co.uk scrape
$amazon_html = file_get_html('http://www.amazon.co.uk/New-Apple-iPod-touch-Generation/dp/B0040GIZTI/ref=br_lf_m_1000333483_1_1_img?ie=UTF8&s=electronics&pf_rd_p=229345967&pf_rd_s=center-3&pf_rd_t=1401&pf_rd_i=1000333483&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_r=1ZW9HJW2KN2C2MTRJH60');
$amazon_pd = $amazon_html->find('b[class=priceLarge]',0)->innertext;
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($amazon_html);
$xpath = new DOMXpath($dom);
$expr = "/html/body/div[#id='divsinglecolumnminwidth']/form[#id='handleBuy']/table[3]/tr[3]/td/div/span";
$nodes = $xpath->query($expr); // returns DOMNodeList object
// you can check length property i.e. $nodes->length
//echo $nodes->item(0)->nodeValue; // get first DOMNode object and its value
$stock_data = $nodes->item(0)->nodeValue;
if ( $stock_data == "In stock." ) {
$stockyesno = "Yes";
} else {
$stockyesno = "No";
}
//Currys scrape
$currys_html = file_get_html('http://www.currys.co.uk/gbuk/apple-new-ipod-touch-8gb-4th-generation-07677427-pdt.html');
$currys_pd = $currys_html->find('p[class=prd-amount]',0)->plaintext;
$currys_stk = $currys_html->find('/html/body/div/div/div[2]/div/div/div[2]/div/ul[2]/li/span')->plaintext;
//span[class=icon icon-check]',0);
echo $currys_stk;
if ( $currys_stk == "Available for home delivery" ) {
$currys_stockyesno = "Yes";
} else {
$currys_stockyesno = "No";
}
//Argos scrape
$argos_html = file_get_html('http://www.argos.co.uk/static/Product/partNumber/9282197/Trail/searchtext%3EIPOD+TOUCH.htm');
$argos_pd = $argos_html->find('span[class=actualprice]',0)->plaintext;
//Ebuyer scrape
$ebuyer_html = file_get_html('http://www.ebuyer.com/product/237805');
$ebuyer_pd = $ebuyer_html->find('span[class=now]',0)->plaintext;
//PcWorld scrape
$pcworld_html = file_get_html('http://www.pcworld.co.uk/gbuk/apple-new-ipod-touch-8gb-4th-generation-07677427-pdt.html');
$pcworld_pd = $pcworld_html->find('p[class=prd-amount]',0)->plaintext;
?>
and then my page where its included, to then which its meant to access the data in the variables from the included file.
<?php include 'scrapedata.php';?>
<!-- MYSQL DATABASE CODE -->
<?php
$db_host = 'localhost';
$db_user = 'admin';
$db_pwd = '1admin';
$database = 'stock_checker';
$table = 'price_stock';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
?>
<!-- MYSQL DATABASE CODE END-->
//Insert the scraped data into the database.
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('Play.com', '$play_pd' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price,stock) VALUES('Amazon', '$amazon_pd', '$stockyesno' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price,stock) VALUES('Currys', '$currys_pd', '$currys_stk' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('Argos', '$argos_pd' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('eBuyer', '$ebuyer_pd' )")
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('PCWorld', '$pcworld_pd' )")
or die(mysql_error());
?>
<!-- MYSQL DATABASE % TABLE CREATION CODE -->
<?php
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<table width='650px'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysql_free_result($result);
?>
Have I done this correctly ? I don't know if they would automattically be included, or they have to be made GLOBAL ?
This is a very bad idea.
You should be using functions; passing and returning values. Include files at the beginning of the script, call functions when needed. Do not put any freestanding (non-function) code in files you include.
(By the way, the next step is OOP and autoloaders.)
And in case you're wondering why this is a very bad idea: I've looked over your code 5 times now (though with no in-depth analysis) and still haven't figured out what variables you want to share between the two files. If I went line-by-line, I'd find it, but I don't want to go line-by-line. Neither do you, in 3 months, when you're updating the code. Make our job easier.
--
From a point of view, an object is a collection of functions and the state they share; so it's the third step here: no functions -> some functions -> functions grouped together in classes. Don't even know if it's any good, but PHP has this to say about OOP. Autoloading is the mechanism PHP uses to load classes on-demand, usually saving you from includes.
They don't need to be imported explicitly.
Try this example:
<?php
// a.php
$myVar = 123;
and
<?php
// b.php
include 'a.php'
echo isset($myVar)?'Included':'Not included';
Related to your posted code: I don't see where you add data to the database. Shouldn't you do that as well?
It's a bad idea to use DOM Parsing for such requests. Amazon released a simple API - read here: http://aws.amazon.com/de/
PHP variables in the included file will appear in the main file by the same name.
But in your code I don't see variables being reused at all? The scrape generates information in variables, then your main file reads an unrelated database table. The two operations need to relate somehow.
I'm new to programming and I need help on my code. I want my page to prompt me if there will be available rooms left. I'm using the onload function on the admin page.
so far here is my code
function prompt()
{
< ?php
include("dbconfig.php");
$sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
?>
if(< ?php $result <= 14 ?>){
alert("Rooms left: < ?php echo $result ?>");
}
else{
alert("Welcome Admin.");
}
}
window.onload=prompt;
edit:
The code worked fine now but it displays "Resource id#4", not the value of the count.
I feel you can't mix php with js codes.
php is mainly on server side , while the js is client side
from the snippet you provide, maybe you should use purely php as follows:
< ?php
include("dbconfig.php");
$sql = "SELECT COUNT(*) FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
if ($result <= 14) {
echo("Rooms left: $result");
}
else {
echo("Welcome Admin.")
}
?>
This should be run at the first when request
I think you are confused about where PHP processes vs. where Javascript processes.
PHP is processed on the server side, while Javascript is processed on the client side. Think of it like this...
You access a page.
Your PHP is processed, and the final output is sent to the browser.
Your Javascript is processed by the browser.
As you have it now, you'd be getting some funny output... especially because of your lack of echo statements. Here is what you'd probably be seeing in your browser page source:
function prompt()
{
if(){
alert("Rooms left: < ?php echo $result ?>");
}
else{
alert("Welcome Admin.");
}
}
window.onload=prompt;
Notice the empty if statement (also the space in the start tags:
if(<?php echo ($result <= 14); ?>){
alert("Rooms left: <?php echo $result ?>");
}
This should make your Javascript evaluate a boolean true/false. Don't forget that Javascript needs to be wrapped in a < script > tag too!
To answer your MySQL question...
Try it like this:
//We can alias the COUNT(*) as MyCount for easy reference
$sql = "SELECT COUNT(*) as MyCount FROM rooms WHERE status = 'available'";
$result = #mysql_query($sql) or die("Could not execute query");
$row = mysql_fetch_array($result); //$row is now an array and will now have your count in it
echo $row['MyCount']; //This will print the count from the database. You could use it in other ways as well.
mysql_query returns resource, not a result.
Try to use:
$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = #mysql_query($sql) or die('Could not execute query');
$count = mysql_result($res, 0, 0);
There should be no space in php tags:
< ?php
^
Should be:
<?php
You are also missing a fetching function, here is how you can get row count in a variable:
<?php $count = mysql_num_rows($result);?>
Later you can use the $count variable in the if condition.
use mysql_fetch_row , and after that in the condition , compare to $row[0]
$sql = "SELECT COUNT(*) FROM `rooms` WHERE `status` = 'available'";
$res = #mysql_query($sql) or die('Could not execute query');
$row = mysql_fetch_row($res);
if(< ?php $row[0] <= 14 ?>){