I am creating a library for PHP scripts and I want to be able to show php code on a html webpage.
I have looked at using highlight_file(); but this will show the whole page
For example, If I have a page called code.php which has an sql query on ( select code from table where sequence = $_GET["id"] ) - example then I use
Highlight_file('code.php?id=123');
This will work but will also show the select query which I do not want to show. I would just want to show the code from the database (code column)
How can I display just the code from the database with the correct colours and formatting etc
UPDATE:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id, $conn)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query,$conn);
$code = mysql_fetch_array($rs);
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id'], $conn);
?>
I have tried the above code, which is just displaying the code in plain text
use highlight_string function, like this:
<?php
highlight_string($code);
?>
where $code is the code you have obtained from your SQL query.
You can create a function around this (something along the following lines):
<?php
function highlight_code_with_id($id, $mysqli) {
$query = $mysqli->query("select code from table where sequence = '$id'");
$code = current($query->fetch_assoc());
return highlight_string($code);
}
// and, use it like this:
echo highlight_code_with_id($_GET['id'], $mysqli);
UPDATE:
Your code is a bit incorrect, you can use:
<?php
$conn=mysql_connect("localhost","charlie_library","Pathfinder0287");
mysql_select_db("charlie_library",$conn);
function highlight_code_with_id($id)
{
$query = "select * from library_php where sequence = '$id' ";
$rs = mysql_query($query);
$code = mysql_fetch_assoc($rs); // change is in this line
echo highlight_string($code["code"]);
}
// and, use it like this:
highlight_code_with_id($_GET['id']);
?>
Note that you do not need to include $conn in your function, it can be ommitted. Also, note that you should use mysqli->* family of functions, since mysql_* family has been deprecated.
Perhaps this would work for you.
This post is originally for HTML, but the answer linked above shows an example using PHP.
Related
hi guy's i have a question.
how to declare a multiple where clause condition inside one php only.
i have try to make my project has a minimum of a php file. i want to make my where clause inside one php file only.
this is the problem i mean. i want to put my code into one php file or inside one <?php ?>. the php code like this
<?php
include("../../Connections/koneksi.php");
$date1= $_POST['date1'];
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='Silo 1'";
$query = mysqli_query($db,$sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($db);
?>
on the code above the query has select table termocouple and the filter of where condition is tanggal and silo. now the problem is i have 12 php file like that. and the different of every php is from the selecting silo, i put Silo 1,Silo 2,Silo 3, ....Silo 12.
please someone help me with this. i want to make it simple in one php file. im really appreciated when you give me an example
In order to minimize your code, if you are using the same query or code more than one time in the same project, it is more recommended to create a function, that you will call anytime you need to execute the code.
So here, since you are using the same query 12 times, you will have to create a function that executes this query, and then call this function every time you want to execute the query.
The function takes parameters, so you will have to give the function the database connection parameter $db in order to connect to the database since you are using this connection inside the function, and then you have to add the values of the where clause to the parameters also.
So your function here will take the database connection $db, $date1 fetched from $_POST, and $silo fetched from $_POST
At the end of the function, you can return any value you wish to return, so in your case, you will have to return the $rows array fetched from the query
Create a common php fileand create a function in it.
Lets say the file name is libraries.php
in this file write the following code:
<?php
function getRows($db, $date, $silo) {
$sql = "SELECT * FROM termocouple where tanggal='$date' AND silo='$silo'";
$query = mysqli_query($db, $sql);
$rows = array();
while($tmp= mysqli_fetch_assoc($query)) {
$rows[] = $tmp;
}
return json_encode($rows);
}
?>
And in each of the files where you are calling the query you will remove the php code and replace it with the following:
<?php
include("../../Connections/koneksi.php");
include("{path-to-file}/libraries.php");
$date1= $_POST['date1'];
$silo = $_POST['silo'];
$rows = getRows($db, $date1, $silo) ;
?>
I am assuming these 12 PHPs are called in diff scenarios. Why dont you pass some param from client side so that the PHP knows which scenario to execute.
$date1= $_POST['date1'];
$silo= $_POST['silo'];//This could be 'Silo 1 OR 'Silo 2' etc.
// Data for Titik1
$sql = "SELECT * FROM termocouple where tanggal='$date1' AND silo='$silo'";
$query = mysqli_query($db,$sql);
I would like to select rows by id and show it. My Table is named text
And this is whats in the table
BookID Type init
Title
Author
PublisherName
CopyrightYeare
here is how i would like to call them
text id 10
by this action i get row nummber 10 and i get all the information in
BookID, Title, Author, PublisherName, CopyrightYeare
If I query this
text id 14
by this action i get row nummber 14 and i get all the information again.
<?php
function text($id){
$query = "SELECT * FROM text WHERE BookID =" .$id ;
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
}
?>
<?php
echo text (14) ;
?>
You have a few problems.
You are using the obsolete mysql_* functions. Consider upgrading to mysqli
You are vulnerable to SQL injection attacks. Again, look at mysqli and read up on how to use prepared statements correctly.
Your function is named text, you are calling displaytext
Your function is not returning a result. At the end of the function, add return $row; to get the results back
You are calling a function called displytext() but the function is called text().
The function text() does not return a value so the echo will have nothing to print.
Sorry for the late reply, just had another gander and here is a working code.
Problems wre
You did not return anything from your functions
You did not escape the $id which would leave it prone to SQL injection
The previously stated function name,
I hope this sorts it for you. See the code bellow
<?php
function text($id){
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM text WHERE BookID = $id";
$row = mysql_fetch_assoc(mysql_query($query));
return $row;
}
print_r(text('1'));
?>
I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
I am trying to grab ad code from my database and echo it on to the page, but for some reason it is not showing up?
$getad = ("SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ");
while($rows = mysql_fetch_array($getad))
{
$code = $rows['code'];
}
$ad1 = $code;
later down the page i print it like this.
<?php print $ad1 ?>
I think your problem is that you don't actually execute the query, you just have saved it in a variable ($getad) and then try to do a fetch af an array containing a string as I see it. If I remeber correctly you have to save you query in a variable, as you did, and then type
$getad = "SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ";
$q = $db->query($getad);
// generate results:
while ($q->fetchInto($row)) {
//display or store
}
You should also include checks, for example that this code has extracted at least one row, or that database connection is working, etcetera.
When I access this from a web browser it returns nothing other than echo'd text, I know this is similar to another question I posted but I can't make sense of it?
<?php
include('config.php');
include('database.php');
class conversion{
public $amnt;
public $cc_from;
public $cc_to;
public function __construct (){
$this->amnt = htmlspecialchars($_GET["amnt"]);
$this->cc_from = htmlspecialchars($_GET["from"]);
$this->cc_to = htmlspecialchars($_GET["to"]);
}
function convert($this->amnt,$this->cc_from,$this-cc_to,$decimals=2){
$db_rate_from = mysql_query("SELECT * FROM _currency WHERE country_code='$this- >cc_from'") or die(mysql_error());;
$query_row_from = mysql_fetch_array($db_rate_from);
$rate_from = ($query_row_from['rate']);
echo $rate_from;
echo "</br>rate to</br>";
$db_rate_to = mysql_query("SELECT * FROM _currency WHERE country_code='$this->cc_to'") or die(mysql_error());;
$query_row_to = mysql_fetch_array($db_rate_to);
$rate_to = ($query_row_to['rate']);
echo $rate_to;
echo "</br>conversion</>";
$conversion = (number_format(($amnt/$rate_from)*$rate_to,$decimals));
echo $conversion;
} }
$var = new conversion();
$var->convert($amnt,$cc_from,$cc_to);
?>
Given this:
$db_rate_from = mysql_query("SELECT * FROM $db_tbprefix WHERE country_code='$this->cc_from'");
where is $db_tbprefix defined? Nowhere, causing your query to be SELECT * FROM WHERE .... If you had proper SQL error handling code, this would've been clear to you. At absolute bare minimum, you should have something like:
$result = mysql_query("...") or die(mysql_error());
which would abort the script on a query failure and tell you exactly why the query failed.
As well, htmlspecialchars is NOT intended for database operations. It does absolutely nothing to prevent SQL injection. For that, you have to use mysql_real_escape_string().
One thing I notice is that you call your method without parameters.
$var->convert();
Yet it is declared to take three mandatory parameters.
function convert($amnt,$cc_from,$cc_to,$decimals=2)
And btw, don't use $query_row_to[rate]. Use either $query_row_to['rate'] or $query_row_to[$rate].
Edit:
How about something like this? Use global $db_tbprefix and skip object orientation.
<?php
include('config.php');
include('database.php');
function convert($amnt,$cc_from,$cc_to,$decimals=2) {
global $db_tbprefix;
$db_rate_from = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_from'") or die mysql_error();
$query_row_from = mysql_fetch_assoc($db_rate_from);
$rate_from = $query_row_from['rate'];
$db_rate_to = mysql_query("SELECT rate FROM $db_tbprefix WHERE country_code='$cc_to'") or die mysql_error();
$query_row_to = mysql_fetch_assoc($db_rate_to);
$rate_to = $query_row_to['rate'];
return number_format(($amnt/$rate_from)*$rate_to,$decimals);
}
echo convert(floatval($_GET["amnt"]), mysql_real_escape_string($_GET["from"]), mysql_real_escape_string($_GET["to"]));
?>
Edit 2: only select what you need, in this case rate. And use mysql_fetch_assoc rather than than mysql_fetch_array which will double your memory consumption and slow down your code.
haven' tested it ... but the possibility i can find is you are passing parameters in function convert while defining it so you need to pass the same param while calling it... OR if the variables are the reference from the predefined one then use them like this
function convert($this->amnt,$this->cc_from,$this->cc_to,$decimals=2){
}