The #mention system does not produce the correct output - php

The following function is not getting a correct results:
function getMentions($content) {
global $db;
$mention_regex = "/#+([a-zA-Z0-9-_]+)/"; //mention regrex to get all #texts
$regexIt = preg_match_all($mention_regex, $content, $matches);
if ($regexIt) {
foreach ($matches[1] as $key => $match) {
if ($key === 0) continue;
$mentioned[] = mysqli_real_escape_string($db, $match[0]);
$match_user = mysqli_query($db, "SELECT user_id, user_name FROM dot_users WHERE user_name IN ('" . implode("','", $matches[1]) . "')") or die(mysqli_error($db));
$userDeti = mysqli_fetch_array($match_user, MYSQLI_ASSOC);
echo $userDeti['user_id'];
echo $userDeti['user_name'];
$match_search = '#' . $match . '';
$match_replace = '<a target="_blank" href="' . $userDeti['user_name'] . '">#' . $userDeti['user_name'] . '</a>';
if (isset($userDeti['user_name'])) {
$content = str_replace($match_search, $match_replace, $content);
}
}
}
return $content;
}
For example, I want to print the user_name and user_id on the screen, but it does not print.
echo $userDeti['user_id']; // echo is empty
echo $userDeti['user_name']; //echo is empty output
Can you tell me what I'm doing wrong or incomplete?

My untested suggestion...
function getMentions($content) {
global $db; // I would rather this be passed as a function argument
if (preg_match_all("/\B#\K[\w-]+/", $content, $matches)) {
if (!$result = mysqli_query($db, "SELECT user_id, user_name FROM dot_users WHERE user_name IN ('" . implode("','", $matches[0]) . "')")) {
// error
} else {
foreach ($result as $row) {
$content = preg_replace("~\B#{$row["user_name"]}\b~", "#{$row["user_name"]}", $content);
}
}
}
return $content;
}
There may be typos, but the general idea is there. Capture mentions and try to avoid emails, look up the ids, replace all mentions.

Related

str_replace() not replacing with <strong> element

I want to be able to create a link as follows, when a user starts typing in a search field. Let's say he types the letter a:
#<strong>a</strong>rig<strong>a</strong>to
PHP:
// sets up database conection to variable $dbh
require_once '../includes/bootstrap.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$tag = (!empty($_GET['tag'])) ? "%$_GET[tag]%" : false ;
if ($tag) {
$stmt = $dbh->prepare('SELECT `tag` FROM `tags` WHERE `tag` LIKE ?');
$result = array();
$stmt->bindParam(1, $tag, PDO::PARAM_STR);
$stmt->execute();
// store result
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row['tag'];
}
$tags = '';
// create links for results
foreach ($result as $value) {
$row = "<li><a href='http://google.com'>" . str_replace($tag, '<strong>' . $tag . '</strong>', $value) . '</a></li>';
$tags .= $row;
}
echo $tags;
}
}
Result of $tags when user types in the letter a:
<li>#arigato</li>
<li>#arizona</li>
<li>#cantalupi</li>
<li>#clearwater</li>
<li>#florida</li>
<li>#happy</li>
<li>#mamadas</li>
<li>#miriam</li>
<li>#nissan</li>
<li>#sauce</li>
<li>#sentra</li>
<li>#usa</li>
<li>#vegas</li>
<li>#was</li>
<li>#watches</li>
For some reason it is not putting in the <strong> tag as desired.
I think this is happening because of this line:
$tag = (!empty($_GET['tag'])) ? "%$_GET[tag]%" : false ;
This variable is used for the MySQL statement, however later on it is also used for the str_replace(), the problem is that it is trying to find %$_GET[tag]% for replacement, not the value in the $_GET variable.
Try this code instead:
// sets up database conection to variable $dbh
require_once '../includes/bootstrap.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$tagStr = $_GET['tag'];
$tag = (!empty($_GET['tag'])) ? "%$_GET[tag]%" : false ;
if ($tag) {
$stmt = $dbh->prepare('SELECT `tag` FROM `tags` WHERE `tag` LIKE ?');
$result = array();
$stmt->bindParam(1, $tag, PDO::PARAM_STR);
$stmt->execute();
// store result
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row['tag'];
}
$tags = '';
// create links for results
foreach ($result as $value) {
$row = "<li><a href='http://google.com'>" . str_replace($tagStr, '<strong>' . $tagStr . '</strong>', $value) . '</a></li>';
$tags .= $row;
}
echo $tags;
}
}

how to check success on insert using OCI

I have the following code but i am not sure how to check if insert is success. execute returns resource id. I would like to check if success and return all errors on fail.
public function persist()
{
$update = FALSE;
if(!is_array($this->tablePrimaryKey)) {
if(!empty($this->fieldVals[$this->tablePrimaryKey])) {
$update = true;
}
}
if ($update) {
$sql = "UPDATE " . $this->tableName . " SET ";
$binds = [];
foreach ($this->fieldVals as $key=>$val) {
if ($key != $this->tablePrimaryKey) {
if(in_array($key, $this->DATE_IDS)) {
$sql .= '"' . strtoupper($key) . '" = sysdate,';
} else {
$bind = 't_' . $key;
$binds[$bind] = $val;
$sql .= '"' . strtoupper($key) . '" = :' . $bind . ',';
}
}
}
$sql = substr($sql,0,-1);
$sql .= " WHERE " . $this->tablePrimaryKey . " = '" . $this->fieldVals[$this->tablePrimaryKey] ."'";
} else {
$binds = $fields = $date_fields = [];
if(!empty($this->tablePrimaryKey) && !is_array($this->tablePrimaryKey)) {
$this->fieldVals[$this->tablePrimaryKey] = $this->generateNewPrimaryKey();
}
foreach ($this->fieldVals as $key=>$val) {
$bind = ':t_' . $key;
if (in_array($key, $this->DATE_IDS)) {
$date_fields[] = strtoupper($key);
} else {
$binds[$bind] = $val;
$fields[] = strtoupper($key);
}
}
$sql = 'INSERT INTO ' . $this->tableName . '("' . implode('","', $fields);
if(count($date_fields) >0) {
$sql .= '","';
$sql .= implode('","', $date_fields);
}
$sql.='") VALUES (' . implode(',', array_keys($binds));
if(count($date_fields) >0) {
$cnt=0;
foreach($date_fields as $date) {
$cnt++;
if(preg_match('/NULL/i', $this->fieldVals[strtolower($date)], $result)) {
$sql .= ",NULL";
} elseif(isset($this->fieldVals[strtolower($date)])) {
$sql .= ",TO_DATE('" . (new DateTime($this->fieldVals[strtolower($date)]))->format("Y-M-d H:i:s") . "', 'yyyy/mm/dd hh24:mi:ss')";
} else {
$sql .= ",sysdate";
}
}
}
$sql .= ')';
}
$this->oiDb->parse($sql, $binds);
return $this->oiDb->execute();
}
I run $result = $oiRequests->hydrate($reportingRequest)->persist();. $reportingRequest is key,value pair of columns/values. $result contains resource id. $oiRequests is my model.
I have tried
$num_rows = oci_fetch_assoc ($result);
print_r($num_rows);
returns
Warning: oci_fetch_assoc(): ORA-24374: define not done before fetch or execute and fetch in /var/SP/oiadm/docroot/dev/uddins/requestportal/requestportal_ajax.php on line 65
Most of the OCI functions return false on error. This means you can do a simple check on the return value and, if it's false, call oci_error().
For the specific case of checking if an INSERT statement worked you can reference the example code for oci_commit(). The relevant part of that example is duplicated here:
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

ajax success function not returning json decoded data

I have searched stackoverflow for similar questions but nothing helped. This is my ajax call to adding.php file. I called this on jquery keyup event. When I inspect in browser I see php file returning response. However, the data in response never reaches success function of ajax.
$.ajax({
url: "anding.php",
type: "POST",
dataType: 'json',
data: JSON.stringify({mycol:mycol,mycolval:mycolval,string:string}),
contentType: 'application/json',
success: function(data){
alert(data);
var output = data.substring(0, data.indexOf('arventures'));
last = data.substring(data.indexOf('arventures') + 10);
last--;
$('.remove').remove();
$('.main_tr').after(output);
if (output == '' || output == null) {
$('.message').html('No results found.');
}
else {
$('#row1').addClass('highlight');
}//highlight row1 by default
}
});
This is my php file which returns the response. I have pasted the entire code because I dont know which part is causing the issue.
adding.php
<?php
include 'connection.php';
$postdata = json_decode(file_get_contents("php://input"), true);
//var_dump($postdata);exit;
//var_dump($postdata);
$query = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '".$table_name."'
AND table_schema = '".$mysql_database."'";
$result = mysqli_query($con,$query);
$results = array();
while ($line = mysqli_fetch_assoc($result)) {
$results[] = $line;
}
$query = null;
foreach ($results as $r) {//search in order.1st search in column 1 then column 2...so on
$append = " SELECT * from " . $table_name . " WHERE " . $r['COLUMN_NAME'] . " like '" . $postdata['string'] . "%'";
$query = $query . $append;
for($i=1;$i<=(count($postdata['mycol']))-1;$i++)
{
$append1=" AND " .$postdata['mycol'][$i]. " like '" . $postdata['mycolval'][$i] . "%'";
$query = $query . $append1;
}
$query=$query." UNION";
}
$query = substr($query, 0, -6);
$result2 = mysqli_query($con, $query);
$pos = strrpos($postdata['string'], '%');
$str_count = substr_count($postdata['string'], '%');
$results2 = array();
$results3 =array();
while ($line = mysqli_fetch_assoc($result2)) {
if (strpos($postdata['string'], '%') !== false || strpos($postdata['string'], '_') !== false) {// highlight in star search
$str = preg_replace('/[^a-zA-Z0-9-]/', '', $postdata['string']);
$line = preg_replace("|^($str)|Ui", "<span class='highlights'>$1</span>", $line);
} else {
$string=$postdata['string'];
$line = preg_replace("|^($string)|Ui", "<span class='highlights'>$1</span>", $line); //highlight in normal search
}
$results2[] = $line;
}
$result2 -> data_seek(0);
while ($line1 = mysqli_fetch_assoc($result2)) {
$results3[] = $line1;
}
for ($i=1;$i<=count($results2);$i++) {
echo "<tr id='row".$i."' class='remove table_row'>";
$j=0;
foreach($results as $r1){
if($j==0){
echo "<td class='index_field' dB_id='".$results3[$i-1][$r1['COLUMN_NAME']]."'>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
} else {
echo "<td>".$results2[$i-1][$r1['COLUMN_NAME']]."</td>";
}
$j++;
}
echo "</tr>";
}
echo 'arventures' . $i;
mysqli_close($con);
Your ajax call never reaches the success function because you have specified dataType as JSON. Either remove dataType or return JSON instead of normal HTML.

Function not returning data as expected

I've got a function that should return me a set of links based on an user id. What the function does momentarily is that it returns me just one link instead a set of links based on an user id. The function looks like this:
function retrieve_image_link($user_id)
{
$query = mysql_query("SELECT `image_link` FROM `imgit_images` WHERE user_id = '" . intval($user_id) . "'");
while ($row = mysql_fetch_assoc($query))
{
$link = $row['image_link'] . '<br />';
}
mysql_free_result($query);
return $link;
}
So this is the code that should get me multiple links instead of just one. Where is the problem that the query returns a string instead of an array?
Please help!
you need to apply links to an array like $array[] = "link";
function retrieve_image_link($user_id)
{
$query = mysql_query("SELECT `image_link` FROM `imgit_images` WHERE user_id = '" . intval($user_id) . "'");
while ($row = mysql_fetch_assoc($query))
{
//add bracktes to $link to return an array
$link[] = $row['image_link'] . '<br />';
}
mysql_free_result($query);
return $link;
}
or use .= opperator if you want all the links in one big string
function retrieve_image_link($user_id)
{
$query = mysql_query("SELECT `image_link` FROM `imgit_images` WHERE user_id = '" . intval($user_id) . "'");
while ($row = mysql_fetch_assoc($query))
{
//add . to = to append string to $link
$link .= $row['image_link'] . '<br />';
}
mysql_free_result($query);
return $link;
}
It seems the problem is here
$link = $row['image_link'] . '<br />';
At the end of the loop, $link should have last value instead of all the values. You have to append each link or create an array to push each link.
$link = $row['image_link'] . '<br />';
You're overwriting the value of $link in the loop. Add [] to make it an array:
function retrieve_image_link($user_id)
{
$query = mysql_query("SELECT `image_link` FROM `imgit_images` WHERE user_id = '" . intval($user_id) . "'");
$link = array( );
while ($row = mysql_fetch_assoc($query))
{
$link[] = $row['image_link'] . '<br />';
}
mysql_free_result($query);
return $link;
}
use .=
function retrieve_image_link($user_id)
{
$query = mysql_query("SELECT `image_link` FROM `imgit_images` WHERE user_id = '" . intval($user_id) . "'");
while ($row = mysql_fetch_assoc($query))
{
$link .= $row['image_link'] . '<br />';
}
mysql_free_result($query);
return $link;
}

When using MySQL request in foreach, first select is good, but then not

With this code:
foreach ($content as $value) {
$data=$value[0];
echo $data;
$req="SELECT * FROM TABLE WHERE data='$data'";
$result=mysql_query($req) or die ('Erreur :'.mysql_error());
if (mysql_num_rows($result)){
echo ' ENTRY EXISTS';
}
else {
echo ' ENTRY DOES NOT EXIST';
}
}
For the first $value it finds an entry, which is correct. For the next ones it doesn't, but it should. How can this be fixed?
Update code
With this code:
$found_list = array();
$fetch_list = array();
foreach($content as $value){
$fetch_list[] = "'" . mysql_real_escape_string($value[0]) . "'";
}
if( empty($fetch_list) ){
echo '<p>No data to fetch</p>';
}else{
$sql = 'SELECT DISTINCT inst_name
FROM INSTITUTS
WHERE inst_name IN (' . implode(', ', $fetch_list) . ')';
$res = mysql_query($sql)
or die ('Error: ' . mysql_error());
while( $row = mysql_fetch_assoc($res) ){
$found_list[] = $row['inst_name'];
}
var_dump($found_list);
}
foreach($content as $value){
echo '<br/>';
echo $value[0] . ' ';
if( in_array($value[0], $found_list) ){
echo "ENTRY EXISTS\n <br/>";
}else{
echo "ENTRY DOES NOT EXIST\n <br/>";
}
}
And the result is :
array(3) { [0]=> string(13) "AixEnProvence" [1]=> string(19) "AixEnProvenceAnnexe" [2]=> string(7) "Acheres" }
acheres ENTRY DOES NOT EXIST
AixEnProvence ENTRY EXISTS
aixenprovenceannexe ENTRY DOES NOT EXIST
instituttest ENTRY DOES NOT EXIST
There is no reason to flood the MySQL server with almost identical queries. Have a look at the IN expression:
SELECT foo, bar
FROM table
WHERE data IN ('a', 'b', 'c');
I also suggest you google for SQL Injection and XSS attacks.
Edit: Here's some code that solves the problem as described in latest comments:
<?php
// $content = ...
$found_list = array();
$fetch_list = array();
foreach($content as $value){
$fetch_list[] = "'" . mysql_real_escape_string($value[0]) . "'";
}
if( empty($fetch_list) ){
echo '<p>No data to fetch</p>';
}else{
$sql = 'SELECT DISTINCT data
FROM table
WHERE data IN (' . implode(', ', $fetch_list) . ')';
$res = mysql_query($sql)
or die ('Error: ' . mysql_error());
while( $row = mysql_fetch_assoc($res) ){
$found_list[] = $row['data'];
}
}
foreach($content as $value){
echo $value[0] . ' ';
if( in_array($value[0], $found_list) ){
echo "ENTRY EXISTS\n";
}else{
echo "ENTRY DOES NOT EXIST\n";
}
}
?>
Answer to updated question:
PHP comparison operators are case sensitive:
<?php
var_dump('Acheres'=='acheres'); // bool(false)
?>
You can use strtolower() to normalize values before comparing.

Categories