replace non breaking space PHP - php

* The json_encode is returning NULL? is NOT the answer. I still receive a NULL when using the json_encode.*
I am very new to PHP, so if you could edit the section with the fixed code, I'd appreciate it.
This is my problem:
When an article under "introtext" contains non breaking lines, it returns NULL. The articles that do not have a non breaking space show up just fine.
This is my question:
How can I get the articles under "introtext" to display properly even if they contain a non breaking space.
Here's the code:
$connection = mysqli_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}else{
//Attempt to select the database
$dbconnect = mysqli_select_db($connection, $db);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}else{
$catID = $_GET['catid'];
$id = $_GET['id'];
$rtn = $_GET['rtn'];
if($id!=""){
$query = "SELECT * FROM tcp_content WHERE id=" . $id . "";
}else{
$query = "SELECT * FROM tcp_content WHERE catid=" . $catID . " ORDER BY publish_up DESC LIMIT " . $rtn . "";
}
$resultset = mysqli_query($connection,$query);
$records = array();
//Loop through all records and add them to array
while($r = mysqli_fetch_assoc($resultset))
{
$r['introtext'] = print_r($r['introtext'],true);
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
here are two links:
This link contains the non breaking space, so you'll notice introtext returns NULL
This link does NOT contain the non breaking space, so you'll notice the article shows

I found this link json_encode problem
see second answer. Charles is suggesting that use iconv() to remove URL encoded non-breaking space.

I finally figured it out and got it working
$r['introtext'] = utf8_encode($r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(160),' ',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(147),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(148),'"',$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(146),"'",$r['introtext']);
$r['introtext'] = str_replace(chr(194).chr(145),"'",$r['introtext']);
$r['introtext'] = htmlentities($r['introtext'], ENT_QUOTES | ENT_IGNORE, "UTF-8");
$records = $r;

Related

Mysqli num rows not working

I have a fairly basic script (i'm used to mysql but i'm moving to mysqli)
<?php
include("../includes/functions.php");
/////////////////////////////////////////////////////////////////////////
$debugMode = 1;
/////////////////////////////////////////////////////////////////////////
if (isset($_GET['u']))
{
// database connection
$c = mysqli_connect("localhost", "xxx", "xxx", "xxx");
// initial query to check if the domain is already in the database
$q = $c->query("SELECT * FROM `domains` WHERE `domain_name`='".trim($s[0])."'");
$v = $q->fetch_assoc();
$r = $q->num_rows;
// check if the string exists in the database
if ($r > 0)
{
// do not enter if greater than 0
} else {
// vars
$u = $_GET['u'];
// DEBUG
if ($debugMode)
{
$fp = fopen('u.txt', 'a');
fwrite($fp, "$u" . "\n");
fclose($fp);
}
// do a split of "|"
$s = explode("|", $u);
// check alexa rank and update
$alexa = alexa_rank($s[0]);
// check connection
if (mysqli_connect_errno())
{
echo mysqli_connect_error();
} else {
// insert query if there is no errors
$i = $c->query("INSERT INTO `domains` (`domain_id`,`domain_name`,`domain_pr`,`domain_alexa_rank`,`domain_moz_da`,`domain_moz_pa`,`domain_date`) VALUES ('','".$s[0]."','".$s[1]."','".$alexa."','".$s[2]."','".$s[3]."',NOW())");
}
}
} else {
header("Location: http://www.site.info/");
}
?>
It looks fairly simple, the problem is the count part isn't working, it's still adding to the database duplicate entries, i also tried:
mysqli_num_rows($q);
This still doesn't seem to work, am i missing something simple?
thanks guys
You should first be sure your query is right.
So please debug your code like that;
$SQL = "SELECT * FROM `domains` WHERE domain_name`='".trim($s[0])."'";
echo "My Query: ". $SQL;
$q = $c->query($SQL);
I guess you have problem on your $s variable. If your sql query is right you can check $v variable have any record if $v variable is an array and have value you have more than one record and you can pass to insert statements if not you can add.
ahh thank you! i found my top query was failing because i was using the explode further down the code! thanks guys.

Can't access the mysqli_result Object of an sql query

Hi I have a problem with this method and it's driving me crazy.The query below should return one field from the database, an id where the filename is matched. Only one value should be returned. When I run the query I get an SQL object returned which looks fine:
mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 0 [type] => 0 )
However I cannot access the above query object no matter what way I try or at least I'm getting no value out of it. I did the exact same to get the package id and it works perfectly.
I used $row = $result_package_id->fetch_array(MYSQLI_ASSOC);
to get the package_id and I tried that for the module_id but it didn't work. Tried the mysqli_fetch_array and it doesn't work either. At a loss of what to do next can anyone help?
ADDED getPackageId method and if statement where the two methods are called. Every time a query is successful the id and package id are retrieved and a new object is created with the two values.
function getId($fileName){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$yModuleId = 0;
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
$result_module_id = mysqli_query($con, $query_module_id);
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
function getYPackageId($package_name){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_packageName = mysqli_real_escape_string($con, $package_name);
$query_package_id = "SELECT id FROM y_package WHERE name='" . $package_name . "'";
$result_package_id = mysqli_query($con, $query_package_id) or die("__LINE__ : " . mysqli_error($con));
while($row_package = mysqli_fetch_array($result_package_id)){
$yPackageId = $row_package['id'];
print_r($yPackageId);
print_r("</br>");
print_r("</br>");
return $yPackageId;
};
}
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
You can use
while ($row = $result->fetch_assoc()) {
$saved[] = $row;
}
but I think from your code displayed a more important issue is that you seem to be mixing procedural and object orientated SQL querying.
So:
1) Rewrite yourcode to use objects, your usage of mysqli_ functions only returns arrays.
2) or alternatively, use the current code as an array because that's what it is, not an object.
Procedural
function getId($fileName){
//this does nothing. Unless this is a custom function?
//$con = connect();
// should be:
$con = mysqli_connect(details,...);
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR); //?
die('Could not connect: ' . mysqli_error($con));
}
//$yModuleId = 0; //unneeded.
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
//add an error feedback for debugging:
$result_module_id = mysqli_query($con, $query_module_id) or die("__LINE__.":".mysqli_error($con));
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
Object Orientated:
$query_module_id = "SELECT id FROM y_module WHERE fileName='?'";
$con = new mysqli($details,...);
$thisQuery = $con->prepare($query_module_id);
$thisQuery->bind_param("s",$sql_filename);
$thisQuery->execute();
while ($row = $thisQuery->fetch_assoc()) {
$saved[] = $row;
}
$thisQuery->close();
From this the $saved variable will be an array of results.
Additional notes:
You are using MySQL COMMIT near the bottom of your code and this is for transactions but you have not shown you've setup or begun any MySQL transactions.
You have a return inside a while statement in getYPackageId which means that the while wil only ever run once because as soon as it reaches the return it will do just that. Bad format.
Remove the semi-colon after the closing bracket of the while statement. This is bad syntax.
I figured out the problem and I feel like such an idiot! The problem was here
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
I was running the commit after I was trying to get the id and package_id from the database that's why I wasn't getting any results. I changed it to this:
if($result_model && $result_package && $result_model_package) {
mysqli_query($con, "COMMIT");
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
It worked perfectly. This is how the getId() method looked when I got it working
function getId($moduleName, $moduleRevision){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_moduleName = mysqli_real_escape_string($con, $moduleName);
$sql_moduleRevision = mysqli_real_escape_string($con, $moduleRevision);
$query_module_id = "SELECT id, module_name, module_revision FROM y_module";
$result_module_id = mysqli_query($con, $query_module_id);
while($row = mysqli_fetch_assoc($result_module_id)){
if($row['module_name'] === $moduleName && $row['module_revision'] == $moduleRevision){
return $row['id'];
}
}
}
Thanks to Martin for all the help and the advice much appreciated! Hope this can help someone by not making the same stupid mistake as me.

Highlight search keyword in PHP does not highlight correctly

I am trying to highlight my search result in PHP search but it highlights undesiraby
I use the code below
//connection to db
define('DB_HOST', 'localhost');
define('DB_NAME', 'dbname');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
//get search term
$searchTerm = $_GET['term'];
$result = mysqli_query($con, "SELECT `location` FROM `locations` WHERE TRIM(location) LIKE '%".($_GET['term'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result))
{
$name = str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>", $row['location']);
array_push($data, $name);
}
//return json data
echo json_encode($data);
Lets say I search for the term makutano
I end up getting a result like the one displayed below:
I would expect it only to highlight makutano, but it does not work as intended.
If i remove the str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>" code my result would be as diplayed in the image below
My database location looks like
Where am i going wrong from my code? Any help will be appreciated
If you want to display the information you have to concatenate a string (which I do with the implode())instead of creating a JSON object:
//get search term
$searchTerm = htmlspecialchars($_GET['term']);
$result = mysqli_query($con, "SELECT `location` FROM `locations` WHERE TRIM(`location`) LIKE '%".($_GET['term'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result))
{
$name = $row['location'];
array_push($data, $name);
}
$string = '"' . implode('","', $data) . '"';
$newString = str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>", $string);
echo $newString;
Once you have created a string then you can do the replace to add the markup to the string.
Your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. I have done the bare minimum in this code by using htmlspecialchars().

how to acess my database elements using the for loop?

I'm learning PHP and I'm well versed with Java and C. I was given a practice assignment to create a shopping project. I need to pull out the products from my database. I'm using the product id to do this. I thought of using for loop but I can't access the prod_id from the database as a condition to check! Can anybody help me?! I have done all the form handling but I need to output the products. This is the for-loop I am using. Please let me know if I have to add any more info. Thanks in advance :)
for($i=1; $i + 1 < prod_id; $i++)
{
$query = "SELECT * FROM products where prod_id=$i";
}
I would suggest that you use PDO. This method will secure all your SQLand will keep all your connections closed and intact.
Here is an example
EXAMPLE.
This is your dbc class (dbc.php)
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getproduct($id) {
//prepared query to prevent SQL injections
$query = "SELECT * FROM products where prod_id=?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
for($i=1; $i+1<prod_id; $i++)
{
$getList = $db->getproduct($i);
//for each loop will be useful Only if there are more than one records (FYI)
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
}
First of all, you should use database access drivers to connect to your database.
Your query should not be passed to cycle. It is very rare situation, when such approach is needed. Better to use WHERE condition clause properly.
To get all rows from products table you may just ommit WHERE clause. Consider reading of manual at http://dev.mysql.com/doc.
The statement selects all rows if there is no WHERE clause.
Following example is for MySQLi driver.
// connection to MySQL:
// replace host, login, password, database with real values.
$dbms = mysqli_connect('host', 'login', 'password', 'database');
// if not connected then exit:
if($dbms->connect_errno)exit($dbms->connect_error);
$sql = "SELECT * FROM products";
// executing query:
$result = $dbms->query($sql);
// if query failed then exit:
if($dbms->errno)exit($dbms->error);
// for each result row as $product:
while($product = $row->fetch_assoc()){
// output:
var_dump($product); // replace it with requied template
}
// free result memory:
$result->free();
// close dbms connection:
$dbms->close();
for($i=1;$i+1<prod_id;$i++) {
$query = "SELECT * FROM products where prod_id=$i";
$result = mysqli_query($query, $con);
$con is the Database connection details
you can use wile loop to loop thru each rows
while ($row = mysqli_fetch_array($result))
{
......
}
}
Hope this might work as per your need..
for($i=1; $i+1<prod_id; $i++) {
$query = "SELECT * FROM products where prod_id = $i";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
}
I think you want all records from your table, if this is the requirement you can easily do it
$query = mysql_query("SELECT * FROM products"); // where condition is optional
while($row=mysql_fetch_array($query)){
print_r($row);
echo '<br>';
}
This will print an associative array for each row, you can access each field like
echo $row['prod_id'];

how to remove anything without numbers and extension with regex?

i have file like this 1248812832.v.doc and i want to remove strings and dots frome database fields to make the file like this 1248812832.doc
i use this code but it not work perfectly i still see strings and dots
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'alsidik';
$conn = mysql_connect($host, $username, $password);
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db($database)) {
echo "Unable to select " . $database . ": " . mysql_error();
exit;
}
$sql = "SELECT * FROM d_jobs";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
$id = $row['jb_id'];
$jb_cv = $row['jb_cv'];
$jb_rep = preg_replace('/[^.a-z0-9.]/','', $jb_cv);
$sql = "UPDATE d_jobs set jb_cv='" .$jb_rep. "' where jb_id=" . $id;
mysql_query($sql);
}
mysql_close($conn);
?>
can anyone help me..thanks
You didn't say how would you want to process this string:
$str = '1212.v.a.doc';
... so I assume you need only the first and the last parts of this string (where parts are delimited by '.' symbols). With this, you can use either...
$parts = explode('.', $str);
if (count($parts) > 2) {
$str = "$parts[0].{$parts[count($parts)-1]}";
}
... or
$str = preg_replace('#(?<=[.])([^.]*[.])+#', '', $str);
The reason for this line to fail:
preg_replace('/[^.a-z0-9.]/','', $jb_cv);
... is that you use a negative character class here (defined by [^...] part). In other words, you erase all symbols but dots, lowercase latin letters and digits from your string. That's definitely not what's wanted, I suppose; in fact, it won't alter the original string in your example at all.
UPDATE: Looks like all that jugglery was in vain, and what you actually needed is just digits and extension. Well, it can be done with regex too:
$str = '1212.v.a.doc';
$str = preg_replace('#^(\d+).*([.][^.]+)$#', '$1$2', $str);
echo $str;
... but in fact I'd prefer the #jeroen's solution for readability alone. )
An alternative to the explode solution: Just cast it to int and put the extension back on:
$str = '1248812832abc.v.doc';
$name = (int) $str . '.' .pathinfo($str, PATHINFO_EXTENSION);
var_dump($name);
Example on codepad.

Categories