MySQL slashes and nl2br - php

I am trying to store HTML posted from a textarea into a database. I have a textarea inside a form which I have called "message". The PHP code that processes it is:
if(isset($_POST['submit'])){
if(isset($_POST['title']) && isset($_POST['message'])){
$title = $_POST['title'];
$message = $_POST['message'];
if(get_magic_quotes_gpc()){
$title = stripslashes($title);
$message = stripslashes($message);
}
$title = mysql_real_escape_string($title);
$message = mysql_real_escape_string($message);
$q = "INSERT INTO table (title,datetime,text) VALUES ('{$title}',NOW(),'{$message}')";
$rows_affected = $db->exec($q);
if($rows_affected > 0){
echo "<p>Done.</p>";
} else {
echo "<p>Failed. </p>";
}
}
}
The problem I am having is then retrieving this and converting newlines to <br />. Here is what I am doing:
$res = array();
$order = array("\r\n","\n","\r");
$replace = '<br />';
$q = "SELECT title,datetime,text FROM table";
$res = $db->get_all($q);
if($res){
foreach($res as $result){
$result['title'] = stripslashes($result['title']);
$result['text'] = str_replace($order, $replace, stripslashes($result['text']));
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
I just can't get rid of those pesky \r\n's in the message. I have tried changing $order to
$order = array("\\r\\n","\\n","\\r");
// and even
$order = array("\\\r\\\n","\\\n","\\\r");
but nothing seems to work. Any ideas?

if ($res = $db->get_all('SELECT title,datetime,text FROM table')){
foreach ($res as &$result){
$result['text'] = nl2br($result['text']);
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
I did three things:
Remove the stripslashes. They mustn't be there. The slashes mysql_real_escape_string adds are removed when the query is executed.
I used the function nl2br for the new lines. Why write something yourself if it's already built in?
I added a & in front of $result in the foreach loop. If I didn't do this only the shallow copies were modified, not the variables themselves. Thus there wouldn't be any change at all.

For the retrieving of the data you don't need to screw around with str_replace/stripslashes.
$res = array();
$q = "SELECT title,datetime,text FROM table";
$res = $db->get_all($q);
if($res){
foreach($res as &$result){
$result['title'] = $result['title']; // Don't see the reason for stripslashes here
$result['text'] = nl2br($result['text']);
}
}
echo "<pre>";
print_r($res);
echo "</pre>";
Use nl2br to convert your \n to proper HTML line breaks. (Note: If you want to show the text inside of a textarea again, e.g. for editing, you need to output the "text" as-is). The only thing that you would want to do is use strip_tags to prevent HTML from being inserted into your output.

more usual way of what nikic did
foreach ($data as $key => $row){
$data[$key]['text'] = nl2br($row['text']);
}
you did overwrite your temporary $result variable, while you have to write modified variable back into array.
and give our variables sensible names.
Also, consider to use htmlspecialchars() if it's user supplied text.

Related

Call array_map multiple times in PHP ( Vlookup in CSV using php array)

I have a problem with RSS parsing in PHP. I need to change some tags in RSS and also assign values to some of the data according to schema provided by another website. I manage to change Country names to ISO with array_map but when I'm trying to reuse the function for another value it's not working. I'm using different .csv files for each array.
Any Ideas ?
Example:
Country name == ISO3 Code
Job Type == Code (Consultancy = 234,Internship = 456 etc).
[CODE]:
$field_country = substr($field_country, strrpos($field_country, "|")+1);
$field_city = $feed[$x]['field_city'];
$field_job_type = $feed[$x]['field_job_type'];
$category = $feed[$x]['category'];
$category = split('[|,]', $category);
$field_job_experience = $feed[$x]['category'];
$field_job_experience = substr($field_job_experience, strrpos($field_job_experience, "Job Level|")+10);
$job_number = $feed[$x]['job_number'];
$pubDate = date('c', strtotime($feed[$x]['pubDate']));
$closeDate = date('c', strtotime($feed[$x]['closeDate']));
echo '<title>'.$title.'</title>';
echo '<pubDate>'.$pubDate.'</pubDate>';
echo '<field_job_closing_date>'.$closeDate.'</field_job_closing_date>';
$csv = array_map('str_getcsv', file('countries.csv'));
$findName= $field_country;
foreach($csv as $values)
{
if($values[1]==$findName)
echo '<field_country>' .$values[2]. '</field_country>';
};
echo '<field_city>'.$field_city.'</field_city>';
$csv = array_map('str_getcsv', file('job_category.csv'));
$findName= $field_job_type;
foreach($csv as $values)
{
if($values[0]==$findName)
echo '<field_job_type>' .$values[1]. '</field_job_type>';
};
echo '<field_career_categories>'.$category[1].'</field_career_categories>';
echo '<field_job_experience>'.$field_job_experience.'</field_job_experience>';
echo '<field_source>1979</field_source>';
echo '<field_theme></field_theme>';
echo '</item>';
}
echo '</channel></rss></xml>';

Array to string conversion issue works before submitting form but not after

Hello I am having trouble with array to string conversion in the following script.
The problem is on the top if statement. For some reason it works fine in the else statement underneath but I keep getting a array to string conversion error when submitting my form and I'm not sure why it works before submitting the form but not after.
The problem is apparently in the first
$content[] = array.
It just returns the word array for $video variable. So where it states the videoid in data-videoID="" it just comes up as data-videoId="Array". Everything esle comes up fine. This would be on line 12 and 13. Here is the code I am using. Im sure it probably something simple that I am overlooking because I am in no way as experienced with php as I probably should be. I have looked over other posts and have tried taking off the brackets and several other things but still cant figure it out. Like I said it works fine if I take out the if statement and just use the else statement. Here is the code.
if(isset($_GET['q'])) {
$keyword_q = $_GET['q'];
$keyword = preg_replace('/\s+/', '/', $keyword_q);
$file = file_get_contents("https://www.googleapis.com/youtube/v3/search?videoEmbeddable=true&videoType=any&part=id%2Csnippet&q=$keyword&videoSyndicated=true&type=video&maxResults=50&key=$key");
$decoded = json_decode($file, true);
$entries = $decoded['items'];
if (!empty($entries)) {
for($i=0; $i<count($entries); $i++) {
$thumb = $entries[$i]['snippet']['thumbnails']['medium']['url'];
$videotitle = $entries[$i]['snippet']['title'];
$videodescription = $entries[$i]['snippet']['description'];
$video = $entries[$i]['id'];
$content[] = "<li><a href='#' data-videoID='$video' class='video-link'><img src='$thumb' alt='Play Video'></a><h3 class='video-title'>$videotitle</h3><p class='video-description'>$videodescription</p></li>";
}
}
$videos = "";
if (!empty($content)) {
foreach($content as $thumb){
$videos .= "$thumb";
}
}
}
else {
$filefeatured = file_get_contents("https://www.googleapis.com/youtube/v3/videos?chart=mostPopular&part=snippet&maxResults=30&key=$key");
$decoded = json_decode($filefeatured, true);
$entries = $decoded['items'];
if (!empty($entries)) {
for($i=0; $i<count($entries); $i++) {
$thumb = $entries[$i]['snippet']['thumbnails']['medium']['url'];
$videotitle = $entries[$i]['snippet']['title'];
$videodescription = $entries[$i]['snippet']['description'];
$video = $entries[$i]['id'];
$content[]= "<li><a href='#' data-videoID='$video' class='video-link'><img src='$thumb' alt='Play Video'></a><h3 class='video-title'>$videotitle</h3><p class='video-description'>$videodescription</p></li>";
}
}
$videos = "";
if (!empty($content)) {
foreach($content as $thumb){
$videos .= "$thumb";
}
}
}

How would I echo this XML data from a database using PHP simpleXML?

I am using a formbuilder plugin in Wordpress which submits the form input to the database as XML data. Now I would like to fetch that data and have it displayed in another page. I have started trying simpleXML to achieve this but now I have hit a road bump.
The XML data that appears in each row of the database follows this format:
<form>
<FormSubject>Report</FormSubject>
<FormRecipient>****#***.com</FormRecipient>
<Name>admin</Name>
<Department>test</Department>
<Value>1000</Value>
<Comments>test</Comments>
<Page>http://***.com</Page>
<Referrer>http://****.com</Referrer>
</form>
I have previously managed to fetch the data that I need using simpleXML from an XML string of the same markup which is in the database but now my question is, how do I do this with a loop for each row in the database?
When the following code is run, wordpress displays a blank page meaning that there is an error:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$string = $statistic->xmldata
$xml = simplexml_load_string($string);
$Name = (string) $xml->Name;
$Department = (string) $xml->Department;
$Value = (string) $xml->Value;
$Comments = (string) $xml->Comments;
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
You are missing ; on line 5
$string = $statistic->xmldata
Should be
$string = $statistic->xmldata;
You should consider enablign WP_DEBUG constant in wp-config.php file. Insert following code to your wp-config.php, just before /* That's all, stop editing! Happy blogging. */
define('WP_DEBUG', true);
/* That's all, stop editing! Happy blogging. */
For more tips on debugging, read the codex
Formbuilder users custom function to extract XML data in formbuilder_xml_db_results Class:
function xmltoarray($xml)
{
$xml = trim($xml);
$match = "#<([a-z0-9_]+)([ \"']*[a-z0-9_ \"']*)>(.*)(</\\1>)#si";
$offset = 0;
if(!preg_match($match, $xml, $regs, false, $offset)) {
return($xml);
}
while(preg_match($match, $xml, $regs, false, $offset))
{
list($data, $element, $attribs, $content, $closing) = $regs;
$offset = strpos($xml, $data) + strlen($data);
$tmp = $this->xmltoarray($content);
$result[$element] = $tmp;
}
return($result);
}
Define that function in your code (before global $wpdb; you don't have to be afraid of same name as that function is defined in Class) and than modify your code in this way:
<?php
global $wpdb;
$statistics = $wpdb->get_results("SELECT * FROM wpformbuilder_results WHERE form_id = '00000000000000000001';");
echo "<table>";
foreach($statistics as $statistic){
$xml = xmltoarray( $statistic->xmldata );
$Name = (string) $xml['form']['Name'];
$Department = (string) $xml['form']['Department'];
$Value = (string) $xml['form']['Value'];
$Comments = (string) $xml['form']['Comments'];
echo "<tr>";
echo "<td>".$statistic->timestamp."</td>";
echo "<td>".$Name."</td>";
echo "<td>".$Department."</td>";
echo "<td>".$Value."</td>";
echo "<td>".$Comments."</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT: edited $xml['Comments'] to $xml['form']['Comments'] and analogous
I fixed it by stripping the backslashes from the XML string using stripslashes()

DOMdocument search for tag

i am trying to do this:
i have several thousand xml files, i am reading them, and i am looking for special text inside an xml with specific tag, but those tags which are having the text i need, are different. what i did till now is this:
$xml_filename = "xml/".$anzeigen_id.".xml";
$dom = new DOMDocument();
$dom->load($xml_filename);
$value = $dom->getElementsByTagName('FormattedPositionDescription');
foreach($value as $v){
$text = $v->getElementsByTagName('Value');
foreach($text as $t){
$anzeige_txt = $t->nodeValue;
$anzeige_txt = utf8_decode($anzeige_txt);
$anzeige_txt = mysql_real_escape_string($anzeige_txt);
echo $anzeige_txt;
$sql = "INSERT INTO joinvision_anzeige(`firmen_id`,`anzeige_id`,`anzeige_txt`) VALUES ('$firma_id','$anzeigen_id','$anzeige_txt')";
$sql_inserted = mysql_query($sql);
if($sql_inserted){
echo "'$anzeigen_id' from $xml_filename inserted<br />";
}else{
echo mysql_errno() . ": " . mysql_error() . "\n";
}
}
}
now what i need to do is this:
look for FormattedPositionDescription in xml and if there is not this tag there, then look for anothertag in that same xml file..
how can i do this, thanks for help in advance
Just check the length property of the DOMNodeList:
$value = $dom->getElementsByTagName('FormattedPositionDescription');
if($value->length > 0)
{
// found some FormattedPositionDescription
}
else
{
// didn't find any FormattedPositionDescription, so look for anothertag
$list = $dom->getElementsByTagName('anothertag');
}

Why not output the first element array?

Why not output the first element array?
i use next code
$product_idn='123112$2313213';
$count_products=substr_count($product_idn,'$')+1;
$idn_products=explode('$',$product_idn);
$name_products='';
$s=0;
while($s<=$count_products){
$prod=$idn_products[$s];
$res10=mysql_query("..... WHERE `product_idn`='$prod'");
$i10=mysql_fetch_assoc($res10);
$name_products.=$i10['name'].', ';
$s++;
}
echo $name_products;
//give 2313213,,
Why not output the first element array ?
What about
$product_idn='123112$2313213';
$idn_products=explode('$',$product_idn);
$name_products='';
foreach($idn_products as $val){
$res10=mysql_query("..... WHERE `product_idn`='$val'");
$i10=mysql_fetch_assoc($res10);
$name_products.=$i10['name'].', ';
}
echo $name_products;
There are a lot of unusual techniques being used in the original code. My best guess at what I'd do, without really knowing the purpose of this code is:
$product_idn = '123112$2313213';
$idn_products = explode('$', $product_idn);
$name_products = '';
foreach($product_idn as $value) {
$res10 = mysql_query("SELECT name FROM ... WHERE `product_idn`='$value'");
if ($res10) {
$i10 = mysql_fetch_assoc($res10);
$name_products .= $i10['name'].', ';
}
}
$name_products = rtrim(', ', $name_products);
echo $name_products;

Categories