I'm working on a Pastebin-esque project in my free time, and last night I solved an issue I've had for a couple of days. (see this thread) However, I managed to mess it all up when I tried to make the code fetch a second column, 'Title'.
Please read the hyperlinked thread and look at Odin's answer or see the code below.
How can I make that code fetch multiple columns?
The code:
viewpaste.php:
require 'connection.php';
$getid = $_GET["id"];
$result=retrieve("SELECT paste FROM pasteinfo WHERE id=?",array($getid));
$row=$result->fetch();
//To get paste column of that id
$paste=$row->paste;
echo $paste;
connection.php:
try{
$db = new PDO('mysql:host=localhost;dbname=database_name;charset=utf8mb4', 'database_username', 'database_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}
function retrieve($query,$input) {
global $db;
$stmt = $db->prepare($query);
$stmt->execute($input);
$stmt->setFetchMode(PDO::FETCH_OBJ);
return $stmt;
}
Just in case you need a little bit more of an explanation of my project, I'm making a pastebin clone (from scratch) and am trying to make a page where a user can enter the id of whatever paste they're wanting to view in the URL and have my code grab all the title and paste data of that id. This should all be done with $_GET, and I had it solved until I realized I never got titles working, and here we are.
Thanks!
Just specify the column in the SELECT query
$result=retrieve("SELECT title, paste FROM pasteinfo WHERE id=?", array($getid));
$row=$result->fetch();
$paste=$row->paste;
$title=$row->title;
Related
I have a simple question. I'm not too good at programming yet but is this safe and correct?
Currently I am using functions to grab the username, avatars, etc.
Looks like this:
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
config.php ^^
function getUsername($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT username FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$name = $stmt->fetch();
return $name["username"];
}
function getProfilePicture($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$image = $stmt->fetch();
return $image["profilepicture"];
}
Is this correct and even more important, is this safe?
Yes, it's safe with respect to SQL injections.
Some other answers are getting off topic into XSS protection, but the code you show doesn't echo anything, it just fetches from the database and returns values from functions. I recommend against pre-escaping values as you return them from functions, because it's not certain that you'll be calling that function with the intention of echoing the result to an HTML response.
It's unnecessary to use is_int() because MySQL will automatically cast to an integer when you use a parameter in a numeric context. A non-numeric string is interpreted as zero. In other words, the following predicates give the same results.
WHERE id = 0
WHERE id = '0'
WHERE id = 'banana'
I recommend against connecting to the database in every function. MySQL's connection code is fairly quick (especially compared to some other RDBMS), but it's still wasteful to make a new connection for every SQL query. Instead, connect to the database once and pass the connection to the function.
When you connect to your database, you catch the exception and echo an error, but then your code is allowed to continue as if the connection succeeded. Instead, you should make your script die if there's a problem. Also, don't output the system error message to users, since they can't do anything with that information and it might reveal too much about your code. Log the error for your own troubleshooting, but output something more general.
You may also consider defining a function for your connection, and a class for your user. Here's an example, although I have not tested it:
function dbConnect() {
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
error_log("PDO connection failed: " . $e->getMessage());
die("Application failure, please contact administrator");
}
}
class User {
protected $row;
public function __construct($userid) {
global $conn;
if (!isset($conn)) {
$conn = dbConnect();
}
$stmt = $conn->prepare("SELECT username, profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$this->row = $stmt->fetch(PDO::FETCH_ASSOC);
}
function getUsername() {
return $this->row["username"]
}
function getProfilePicture() {
return $this->row["profilepicture"]
}
}
Usage:
$user = new User(123);
$username = $user->getUsername();
$profilePicture = $user->getProfilePicture();
That looks like it would work assuming that your config file is correct. Because it is a prepared statement it looks fine as far as security.
They are only passing in the id. One thing you could do to add some security is ensure that the $userid that is passed in is the proper type. (I am assuming an int).
For example if you are expecting an integer ID coming in and you get a string that might be phishy (possible SQL injection), but if you can confirm that it is an int (perhaps throw an error if it isn't) then you can be sure you are getting what you want.
You can use:
is_int($userid);
To ensure it is an int
More details for is_int() at http://php.net/manual/en/function.is-int.php
Hope this helps.
It is safe (at least this part of the code, I have no idea about the database connection part as pointed out by #icecub), but some things you should pay attention to are:
You only need to require your config.php once on the start of the file
You only need to prepare the statement once then call it on the function, preparing it every time might slow down your script:
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. - PHP Docs
(Not an error but I personally recommend it) Use Object Orientation to help organize your code better and make easier to mantain/understand
As stated by #BHinkson, you could use is_int to validate the ID of the user (if you are using the IDs as numbers)
Regarding HTML escaping, I'd recommend that you already register your username and etc. HTML escaped.
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
Hy everyone, I can't wrap my head around this. I'm trying to get some data from a table using PDO. this is my code:
//in db.php I have the connection:
$host = 'localhost';
$db = 'APL';
$dbuser = '';
$pass = ' ';
try{
$conn = new PDO("mysql:host=$host;dbname=$db", $dbuser, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
//in my file I have this:
$id = $_GET['id'];
$sel_sql = "SELECT * FROM users WHERE id =:id";
$stmt = $conn ->prepare($sel_sql);
$stmt -> bindParam(':id', $id);
$stmt -> execute();
$result = $stmt -> fetchAll(PDO::FETCH_ASSOC);
The problem is that print_r($result) returns '1' (just the value 1, therefore I can't access any data stored in the table) as long as $_SESSION['user'] is set.
The whole data-retrieving worked just fine if the $_SESSION['user'] is not set.
Can someone please explain why this is happening? (I'm fairly new to all this and I'm really trying to understand why some issues occur).
Thank you!
The fetchAll function should be returning either an array, or a boolean FALSE.
You report that print_r($result) is displaying an integer value of 1.
I don't see how that's possible, unless you are assigning a different value to $result. Try relocating print_r($result) to immediately follow the assignment from fetchAll.
(My suspicion is that $result is being assigned a value of 1 elsewhere in your code, before you do the print_r. If there were "Issues with php connection to MySQL database", we'd be expecting to see a PDO error of some sort.)
NOTE: I don't think PDO::FETCH_ASSOC is a defined fetch style for the fetchAll function. (fetchAll has different fetch styles than fetch.)
Just in case someone else stumbles upon this, between the $result variable and the print_r($result) I had an include_once(); statement (which was wrongly put there in the first place).
Thank you everyone for your answers.
I am starting to learn php PDO because I've read that it is more efficient and secure.
I could do the following with simple mysqli but am having trouble making it work with PDO.
PID stands for an id number.
fname stands for: first name.
lname stands for: last name.
age stands for ... age.
Basically I have an index.php that contains links from a test table called "persons" inside of the database drinks. When I click on the link which shows the fname of every row, it goes to insertcarbonated.php which is then supposed to $_GET['fname']; of the link and search up that specific row. However, my code in insertcarbonated.php is not working and I am not familiar enough with PDO to know exactly why, I would like some enlightenment on this because I literally begun learning PDO yesterday. :(
Here is my insertcarbonated.php:
<html>
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'theusername';
/*** mysql ***/
$password = 'thepass';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
/*** The SQL SELECT statement ***/
$fname = $_GET['fname'];
//is _GET even working with PDO?
$STH = $dbh-> prepare( "SELECT * FROM persons WHERE fname LIKE '$fname'" );
/***as Joachim suggested, I had actually two different variables here, however, it
did not solve the issue **EDITED** from ($DBH to $dbh)****/
$STH -> execute();
$result = $STH -> fetch(0);
//$result should print out the first column correct? which is the person's ID.
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<head>
</head>
<body>
<p><?php print $result; ?></p>
//me trying to print out person's ID number here.
</body>
</html>
As previously mentioned, I'm not sure where my error is, I get fatal error:
Call to a member function prepare() on a non-object?
and If I try to not use that function, my page is simply blank and nothing prints out.
Basically I would just like to print out different bits of information from that row (that is from it's relevant link in index.php). I would like to know how to solve this using PDO.
Here is the previous question I asked, and it was solved but not with PDO.
Previous question
You could do something like this...
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
$fname = $_GET['fname'];
$sth = $dbh->prepare("SELECT * FROM persons WHERE fname LIKE ?");
$sth->execute( array($fname) );
$result = $sth->fetch(PDO::FETCH_OBJ); // or try PDO::FETCH_ASSOC for an associative array
}
catch(PDOException $e)
{
die( $e->getMessage() );
}
In the HTML part you can do print_r($result) and you will see the exact structure of your results.
Comments: one of the best reasons to use PDO is the automatic escaping of the dynamic user inputs, like $fname here, so you should use it. Also, with $sth->fetch($param) the $param is not the column number but the type of the fetch method PDO will use (see PHP manual). Depending the method, you can get the PID of the result by $result->PID in case of PDO::FETCH_OBJ or by $result['PID'] when using PDO::FETCH_ASSOC. I hope this helps.
I built a blog that uses a WYSIWYG editor(TinyMCE). You build a blog post, post it, and it is stored in a MySQL Database. The post then gets pulled out by another page. Simple stuff for most of you I'm sure.
It worked fine on my test server, so I switched it to another server, and now the images don't pull through properly on the view blog page.
I inspected the img URL and it looked like this.
<img src="\"/img/parking1.png\"" alt="\"\"">
I haven't written a method to do it, but it seems to be escaping () the quote marks.
It didn't do this on my last server, and worked fine, so I am assuming it's a server (hosting) security thing.
I tried to remove them, replace them with blank:
$cleanpost = str_replace('\', '',$post);
Where $post is the data pulled from the DB. It's bad syntax and putting the back-slash in between the quotes breaks it.
Can anyone tell me how to do this please? Or am I even correct as to think this is what I should be doing?
Much thanks.
EDIT: PHP code for blog post insert
if (isset($_POST['blogpost'])) {
$nowdate = new DateTime('NOW');
$thisdate = $nowdate->format('Y-m-d H:i:s');
$post = $_POST['blogpost'];
$title = $_POST['posttitle'];
$status = 'yes';
try {
$conn = new PDO('mysql:host=host;dbname=dbname', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('INSERT INTO blogposts(posttext, thisdate, posttitle, active) VALUES(:post, :postdate, :posttitle, :status)');
$stmt->execute(array(
':post'=>$post, ':postdate'=>$thisdate, ':posttitle'=>$title, ':status'=>$status
));
//echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
echo 'died';
};
}
You can use stripslashes() to unescape the string.
$post = stripslashes($post);
Try this
$cleanpost = str_replace('\"', '',$post);