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.
Related
I want know if there is a function in MySQLi that will let me to look for a words that contain a single quote.
An example is better than hundren explaination, here is it:
-> First
I receive a word to search in PHP (Ex: Example's containing quote)
I have a function that remove all quote (') from any received text string
And then i perform a search in the MySQL database, but the value in the MySQL database contain the QUOTE.
So, i receive the data like this:
$text_to_search = "Examples containing quote"; // Removed the quote
Column in database = "Example's containing quote";
How to remove the quote in database so i can compare it to the received text string with quote removed ?
Do SOUNDEX will work in my case ?
Thank's in advance.
You can conditionally check for both versions of your string. Query for one or two values depending on the existence of a single quote.
Untested code:
$config = ['localhost', 'root', '', 'dbname'];
$search = "Examples containing quote";
$values = [$search];
if (strpos($search, "'") !== false) {
$values[] = str_replace("'", "", $search);
}
$count = sizeof($values);
$placeholders = implode(',', array_fill(0, $count, '?'));
$param_types = str_repeat('s', $count);
if (!$conn = new mysqli(...$config)) {
echo "MySQL Connection Error: <b>Check config values</b>"; // $conn->connect_error
} elseif (!$stmt = $conn->prepare("SELECT * FROM tablename WHERE columnname IN ($placeholders)")) {
echo "MySQL Query Syntax Error: <b>Failed to prepare query</b>"; // $conn->error
} elseif (!$stmt->bind_param($param_types, ...$values)) {
echo "MySQL Query Syntax Error: <b>Failed to bind placeholders and data</b>"; // $stmt->error;
} elseif (!$stmt->execute()) {
echo "MySQL Query Syntax Error: <b>Execution of prepared statement failed.</b>"; // $stmt->error;
} elseif (!$result = $stmt->get_result()) {
echo "MySQL Query Syntax Error: <b>Get Result failed.</b>"; // $stmt->error;
} else {
$resultset = $result->fetch_all(MYSQLI_ASSOC);
echo "<div>Numrows: " , sizeof($resultset) , "</div>";
foreach ($resultset as $row) {
echo "<div>Row: {$row['columnname']}</div>";
}
}
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().
Dealing with iptables and php / mysql but no luck, I'm trying to find an solution to add blocked ip's ( yes, more than one at once ) from iptables to mysql. Is anyone able to help with this issue?
<?php
$hostname = gethostname();
$name = permanent;
require_once("/etc/blocked/inc/config.inc.php");
$output = shell_exec('iptables -S permanent');
$lines=explode("\n",$output);
$fail=array();
$r="/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/";
foreach($lines as $line){
$t=array();
preg_match($r,$line,$t);
$ip=$t[0];
$fail[0]=$ip;
if ($fail[0] == '') {
}
else {
#echo "$hostname,$fail[0],$name \n";
$query = "INSERT INTO blockedips (hostname,ip,name) VALUES ('$hostname','$fail[0]','$name')" ;
$result = mysqli_query($link,$query) or die('Query failed: ' . mysqli_error($link));
mysqli_close($link);
exit;
}
}
?>
Alright, I've got some time to kill. I suggest you read up on how to use preg_match(), as well as reconsider how you're treating your database connection. I also corrected a bunch of other small mistakes and needless code.
<?php
$hostname = gethostname();
// this needs to be quoted
$name = "permanent";
require_once("/etc/blocked/inc/config.inc.php");
// specify the full path to your binary
$output = exec("/sbin/iptables -S permanent", $lines);
// exec will create an array
//$lines=explode("\n",$output);
// you weren't capturing the IP address here
$r="/((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))/";
foreach($lines as $line){
// this can create itself
// $t=array();
// why aren't you checking the results of this call?
if (preg_match($r, $line, $t)) {
// $t[0] is the whole string, $t[1] is the first match
$ip = $t[1];
// I don't know why you were re-assigning this to another array
// $fail[0]=$ip;
#echo "$hostname,$ip,$name \n";
$query = "INSERT INTO blockedips (hostname,ip,name) VALUES ('$hostname','$ip','$name')";
$result = mysqli_query($link,$query)
or die('Query failed: ' . mysqli_error($link));
// why close your database? your second query isn't going to work too well
// mysqli_close($link);
// oh, will never be a second value. is this intentional? why have a loop then?
// exit;
}
}
?>
But wait! Prepared statements are made to be prepared once and executed repeatedly, while reducing system overhead. I'd also strongly suggest migrating to PDO, or at least use the mysqli object-oriented interface.
<?php
$hostname = gethostname();
$name = "permanent";
require_once("/etc/blocked/inc/config.inc.php");
$output = exec("/sbin/iptables -S $name", $lines);
$stmt = $link->prepare("INSERT INTO blockedips (hostname,ip,name) VALUES (?, ?, ?)";
$octet = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
$ip = "$octet\.$octet\.$octet\.$octet";
foreach($lines as $line){
if (preg_match("/($ip)/", $line, $t)) {
$ip = $t[1];
$stmt->bind_param("sss", $hostname, $ip, $name);
if ($stmt->execute() === false) {
echo 'Query failed: ' . $link->error();
$link->close();
exit;
}
}
}
?>
HTML FILE:
<form method="post" action="generate.php">
Product Reference(s): (if multiple, separate by ",")<br />
<input type="text" name="project_ref" value="REF123, REF124" />
<input type="submit" value="Generate" />
</form>
PHP FILE:
<?php
$ref_array = explode(',', $_POST['project_ref']);
foreach ($ref_array as &$ref) {
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference = '$ref' LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
}
?>
RESULTS:
Brand: Bose
0 results
But I actually wanted:
Brand: Bose
Brand: Beats
So the problem is that the MySQL query is not running for every array item. Its only executing the first item of the array.
Your input value has a space between the different refs: REF123, REF124
You can either explode on a comma & space:
$ref_array = explode(', ', $_POST['project_ref']);
Or trim the values:
$sql = "SELECT * FROM `inventory` WHERE reference = '" . trim($ref) . "' LIMIT 1";
It's also strongly recommended that you pass in $ref as a parameter, rather than a string literal:
http://php.net/manual/en/mysqli-stmt.bind-param.php
It looks like your issue is in your explode. The first value of the explode is correct the second (third, forth, etc.) will have a leading space. explode on ', ' instead of ',' or trim the results before using it.
But there are a few other things in this code. Don't create a new connection for each query, the single connection will work just reuse it. Second, use parameters or sanitize the value before you use it in the sql, this will help prevent sql injection attacks, a better way is to use PDO and use parameters. Last, change your query so that a single query returns all the results you need by using an IN clause.
<?php
$ref_array = explode(', ', $_POST['project_ref']);
$ref_IN = "";
foreach ($ref_array as $ref_val)
$ref_IN .= "'{$ref_val}', ";
$ref_IN = rtrim($ref_IN , ",");
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `inventory` WHERE reference IN ({$ref_IN}) GROUP BY reference";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Brand: " . $row["brand"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
* 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;