I'm using PDO to query some data from my database but I have a section with raw php code that doesn't show up, only in the source as if it's trying to run.
I have the slashes stripped and I have it echoed under pre/code tags so I'm wondering as to why it won't show on the page.
Database
id name(VARCHAR) code (LONGTEXT)
1 test <?php echo /'hello world/'; ?>
PHP File
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=$dbname;charset=utf8', '$username', '$password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$stmt = $db->prepare('SELECT name, codeOne FROM table_one WHERE id = :id');
$stmt->bindParam(':id', '1');
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'] . '<pre><code>'. stripslashes($row['codeOne']) .'</code></pre>';
}
} catch(PDOException $e) {
return $e->getMessage();
};
?>
What Everyone Sees
test
View Source
test<pre><code><?php echo "Hello";?></code></pre>
Well just use htmlspecialchars() to encode your string, e.g.
echo htmlspecialchars('<?php echo "Hello";?>');
What you see:
<?php echo "Hello";?>
Source code:
<?php echo "Hello";?>
OR if you want to be really fancy you could use: highlight_string(), which also gives some nice color to your string:
echo highlight_string('<?php echo "Hello";?>', TRUE);
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below.
Here is my php file;
<?php
$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$sql="SELECT id,planname,price FROM plan";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=planname value=''>Plan Name</option>"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[planname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
if(isset($_REQUEST['planname'])){
// connection should be on this page
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
$res = mysql_fetch_assoc($sql);
echo $res['price'];die;
}
echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';
?>
I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
You are searching in the column planname, but by defining the <option>'s as
echo "<option value=$row[id]>$row[planname]</option>";
You are sending the id as value.
So your query should be:
$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));
Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?
The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.
How to do implement your plan
You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)
1. The frontend:
As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).
To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.
So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.
Note:
I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp
I think you should check out jQuery if you haven't yet, it makes things really really easy.
Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.
I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>
2. The backend: (in this case called ajax.php)
A simple piece of code, nothing special to do.
First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.
Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.
Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.
Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}
$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}
function query(){
$leverancierVar = mysql_query("SELECT * FROM leverancier");
while($record = mysql_fetch_array($leverancierVar)){
echo '<option value="' . $record['leverancier'] .'">' . $record['leverancier'] . '</option>';
}
}
this is my code to store all data in database in function
<select id="leverancier" name="leverancier" style="width: 30%">
<?php query() ?>
</select>
this is the line of code i am using in the form to load data
[Database screenshot][1]
When I click the form dropdown button, there is no data displayed.
I am trying to solve the issue for a few hours, maybe someone with a clear look can see the mistake I made.
Edit:
I managed to get the data from the database, and displayed in a the dropdown, however the text is not displayed in the dropdown. You can however choose a value, and the correct value will be saved in the database. Here is a picture of the problem
And here's the code I used:
<?php
$mysqli = new mysqli("localhost", "root", "", "voorraad");
$result = $mysqli->query("SELECT leverancier from leverancier");
echo "<select id='leverancier' name='leverancier' style='width: 30%', color='black'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['leverancier'] ."'></option>";
}
echo "</select>";
?>
I imagine you're not connected to the database, probably worth looking over the connection page in the PHP manual
In the manual you will probably notice some warnings about the mysql_* extension. That is because it is deprecated and removed in version 7 and above. What does that mean for you? Essentially you shouldn't be using the mysql_* extension in your code.
You should instead use mysqli or PDO
If you were going to use PDO you would connect like so:
$dsn = 'mysql:dbname=<DATABASENAME>;host=<HOSTADDRESS>';
$user = ''; // Database User
$password = ''; // Database Password.
try {
$connection = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
// Connection failed, you may want to do something here
}
And then do your query like so:
$statement = $connection->prepare('SELECT * FROM leverancier');
$statement->execute(); // Run the query.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo '<option value="' . $record['leverancier'] .'">' . $record['leverancier'] . '</option>';
}
So basically whenever I click a button the counter will go up and save it to a mysql database. Heres what I have so far but it doesn't echo the number it gives no errors.
try {
$db = new PDO('mysql:host=localhost;dbname=mydatabse;charset=utf8', 'myusername', 'password');
} catch(Exception $e) {
die('Error : '.$e->getMessage());
}
if( isset($_POST['clicks']) ) {
$sql = "UPDATE clicks SET clicks=clicks+1";
$result - $db->query($sql);
}
$row = $db->query('SELECT * FROM clicks');
while ($data = $row->fetch()) {
echo $data["clicks"];
}
I don't know if the clicking part works either due to nothing ebing echoed...
The sql table is: Big int 20 clicks
fix this:
$result - $db->query($sql);
to this:
$result = $db->query($sql);
Maybe you dont reload the page onclick so echo does not work
Try adding this instead of your echo and see if it works:
$clicks = $data["clicks"];
echo "<script language='JavaScript' type='text/javascript'>";
echo "alert('$clicks');";
echo "</script>";
Referring to this topic: Display error message if value not found mysql,
I tried to understand what's the correct method to achieved it, my current code show's me the result from database query but when I put some value that not in database, it just doesn't show the error message or any php coding error.
Here is my php code:
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'dbconnect.php';
$name = $_POST['name'];
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT *
FROM customer
WHERE lname LIKE :name OR
fname LIKE :name OR
number LIKE :name";
$q = $conn->prepare($sql);
$q->execute(array('name' => $name));
$q->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
and here is my html view:
<tbody>
<?php
$cs = $q->fetchAll();
if ( $cs === FALSE ) {
echo "The search of $name return no result";
} else {
foreach($cs as $r): ?>
<tr>
<td><?php echo htmlspecialchars($r['fname']), ' ', htmlspecialchars($r['lname']) ?></td>
<td><?php echo htmlspecialchars($r['number']) ?></td>
<td>View Profile</td>
</tr>
<?php endforeach;
} ?>
</tbody>
Kindly advise where did I go wrong?
Technically, nothing is failing with the query itself, so fetchAll() won't return false. What it will do, when you run a query that returns no results, is return an empty array.
In this case, you can alter your if statement to read: if ($cs === false || empty($cs)) {. Alternatively, you can use if (!$cs) { to allow PHP to interpret falsey values, like an empty array.
Source: PDOStatement::fetchAll()
I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the table2 where the column id = 340 and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the users which updates the new values to the table1 with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
For example lets say I have 3 fruits in the table and I select pear it updates the table with a "1" instead of the word "pear"
apple
pear
peach
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Slot1 : <select name="slot1">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM table2 where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$slot1 = 0;
foreach($rowarray as $row)
{
echo "<option value = $slot1 >$row[FirstName] $row[LastName]</option>";
$slot1++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE table1 SET Slot1place = :slot1 WHERE ID = '340'");
$stmt->bindParam(':slot1', $slot1,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
You dont use sqlite_escape_string if youre using a prepared statement like that. The values are going to be quoted witn they are bound to the statement.
I think you should check your html syntax (Is it missing tags, and the ).
Check it out at: http://www.w3schools.com/html5/tag_option.asp
echo "<option name = $name >$row[FirstName] $row[LastName]</option>";
Everything else is the right syntax