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);
Related
Here's my code:
<?php
//recently added
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if ($result == 1){
?>
<script>
jQuery(document).ready(function(){
jQuery(".eltdf-psc-slide").addClass("no-background");
});
</script>
<?php
}
//=============
?>
Basically what I'm trying to do is checking and see if the value stored in the $shadowless_background_table "DB" is == 1 and I only want that column (background). I have browse the web, but what I see are examples with while loops which I was wondering if I could do something like this instead.
If you want to fetch a single record based on a condition you can do this -
$result = mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
if (mysql_num_rows($result)>0){
$fetchedColum = mysql_result($result, 0, 'COLUMN_NAME');
}
There are couple of issues with your code.The first thing that i have noticed is that you are using mysql API instead of PDO.I don't blame you since the internet is full of old tutorials and you probably didn't have a chance to get some guidance.
MySql is getting old It doesn't support modern SQL database concepts such as prepared statements, stored procs, transactions etc... and it's method for escaping parameters with mysql_real_escape_string and concatenating into SQL strings is error prone and old fashioned.
Organize your project better.
As i have seen from this example you probably have a poor project organization.You should consider reading about PSR Standards
And to go back to your question ,and to update it a bit.
Instead of doing
mysql_query("SELECT background FROM " . $shadowless_background_table . " WHERE id = 1");
I would do it this way:
<?php
$host = "localhost";
$username = "user name of db";
$password = "password of db";
$dbname = "database name ";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//your data
$id = 1; // id
$stmt = $conn->prepare("SELECT background FROM database_name WHERE id=:id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row) {
echo $row["row_name"];
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
Go read more about PHP in general ,it will help you out a lot.The biggest problem is that there are so much wrong tutorials and references or they are just old.And people learn from wrong sources.
I had the same problem ,but thanks to right people on this site i have managed to learn more.
My suggestion is that you read about PSR,PDO and PHP in general!!!
Also a thing you should consider reading about is security in php.
Good luck mate :D
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;
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>
I'm inserting data into my database as a string. The link column is latin1_swedish_ci. I tried changing it to UTF8_swedish_ci (that didn't help). I'm inserting a link and it gets inserted completely how it is. I'm passing this link to a php file which is a popup and then outputting it on the screen. During the output, if any of the links contain www.blahblah.com/somethingUTF8...there is more after UTF8 in the database but not on the screen. Sorry for the long explanation...here's the code:
Inserting into DB:
$xml = simplexml_load_file($feed);
foreach ($xml->channel->item as $list){
$stmt = $mysqli->prepare ("INSERT INTO some_db (title, am_desc, link) VALUES (?,?,?)");
$stmt->bind_param("sss", $title, $am_desc, $link);
$title = $list->title;
$am_desc = $list->description;
$link = mysqli_real_escape_string($mysqli, $list->link);
$stmt->execute();
$stmt->close();}
This is how I call the popup after running the mysqli_fetch_array to the the link:
<div style='position:relative; left:140px; padding-bottom:10px;
width:100px'><a href='popup.php?link=".$link."'
onClick='popup(this.href); return false;'>Click To Order</a></div>
And this is how I'm getting the code passed from the link in the popup:
$link = $_GET['link'];
It works for every link that does not have the UTF8. I'm pretty new at this and the solution might be simple but I haven't been able to find it for hours. Please help!
Try $link = utf8_encode($_GET['link']); .....that should do the trick ;)
I have a CMS that its administrator must use it to insert some website gadgets written in JavaScript to its database MySQL. I've used PDO for this, but it puts back slashes before all quotation marks (When I run the project on the internet). So codes appear like this in the source:
<script type=\"text/javascript\" src=\"something.js\"></script>
Therefore, nothing will be shown in the page. Wheras this back slashes don't be applied when I test the application locally, and I'm able to see these gadgets in the page.
Actually, I have same codes that acts in different manners on different locations (Local and Remote). What's the problem?
This is my code:
try
{
$db = new PDO("mysql:host=$hostname;dbname=dbdirectory", $username, $password, array(PDO::ATTR_PERSISTENT => true));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_BOTH);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$title = $_POST['title'];
$code = $_POST['code'];
$sql = "INSERT INTO tbl_services (title,code) VALUES (?,?)";
$q = $db->prepare($sql);
$q->execute(array($title,$code));