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;
}
}
Related
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.
I need some help please.
Currently my mariadb is set up with one column as a json array.
I would like to search the array from a users input, then combine it with the first and last name of the user stored in the database.
In the database:
Columns: firstname, lastname and suburbs_i_cover (containing the json array)
ex: ["Pretoria","Cape Town","Garden Route"]
I would like the sql statement that would search the suburbs_i_cover and allow me to combine the first and last name.
So far I have this:
<?php
//echo JUri::getInstance();
if (isset($_GET['category'])) {
$catetogry = $_GET['category'];
$name = $_GET['name'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = ("SELECT * FROM #__jsn_users"); //not sure what goes here
$db->setQuery($query);
$results = $db->loadObjectList();
foreach($results as $obj) {
$value = json_decode($obj->suburbs_i_cover);
$value = array_filter($value, 'strlen'); //removes null values
but leaves "0"
$value = array_filter($value); //removes all null
values
if (!empty($value)) {
$value2 = $obj->firstname;
$value3 = $obj->lastname;
echo $value2 . ' '. $value3;
//echo "<br>";
// echo sizeof($value);
echo "<br>";
if (is_array($value)) {
foreach ($value as $sub_value) {
echo $sub_value;
echo "<br>";
}
}
echo "<br>";
echo "<hr>";
}
}
}
I got a working solution:
To use: in_array($name, $value)
<?php
//echo JUri::getInstance();
if (isset($_GET['category'])) {
$catetogry = $_GET['category'];
$name = $_GET['name'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = ("SELECT * FROM #__jsn_users");
$db->setQuery($query);
$results = $db->loadObjectList();
foreach($results as $obj) {
$value = json_decode($obj->suburbs_i_cover);
$value = array_filter($value, 'strlen'); //removes null values
but leaves "0"
$value = array_filter($value); //removes all null
values
if (in_array($name, $value)) {
$value2 = $obj->firstname;
$value3 = $obj->lastname;
echo $value2 . ' '. $value3;
echo "<br>";
echo "<hr>";
}
}
}
?>
How to insert parsed data in mysql, but before we need to check if record exist or not.
And I need to record item parsed description to item with parsed ID.
For example on my DB I have a lot of products with ID and another column and with empty "description" column. And I need to feel this empty column with current decsription.
include 'simple_html_dom.php';
$db = mysqli_connect('localhost', 'mysql', 'mysql', 'database');
$site = 'http://optnow.ru/catalog';
$data = file_get_html($site);
$catalogLink = array();
$i = 0;
if(!empty($data)) {
foreach($data->find('div.cat-name a') as $catalog) {
$catalogLink['url'] = $catalog->href;
$urls[] = $catalogLink;
}
foreach($urls as $url => $k) {
foreach($k as $n) {
$catalogLink = 'http://optnow.ru/' . $n . '?page=0';
$productData = file_get_html($catalogLink);
foreach($productData->find('.link-pv-name') as $link) {
$productLink['url'] = $link->href;
$productUrls[] = $productLink;
}
foreach($productUrls as $href) {
$link = 'http://optnow.ru/' . $href['url'];
$product = file_get_html($link);
foreach($product->find('.block-d .btns-d .btn-buy') as $productId) {
if(!empty($productId)) {
$dataId = $productId->{'data-offerid'};
}
}
foreach($product->find('.description div div p') as $description) {
if(!empty($description)) {
$query = "INSERT INTO snowcore_parser_products (`description`) WHERE `remote_id` = " . $dataId . " VALUES (" . $description->plaintext . "');";
$sql = mysqli_query($db, $query);
print_r($sql);
}
}
}
}
}
}
Currently I use MySQLi and I try to convert all my MySQLi to PDO.
In MySQLi I have this code and it work very fine:
// connection string in MySQLi
if ($query = $connection->prepare("SELECT u.ID as ID,
u.Username as Username,
u.Firstname as Firstname,
u.Lastname as Lastname,
// ... many more
FROM Users u
INNER JOIN Gender g ON u.Gender = g.id
// ... many more
WHERE u.ID = ?")) {
$query->bind_param('s', $_SESSION['ID']);
$query->execute();
$metaResults = $query->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams = '';
foreach ($fields as $field) {
if (empty($statementParams)) {
$statementParams.="\$column['" . $field->name . "']";
} else {
$statementParams.=", \$column['" . $field->name . "']";
}
}
$statment = "\$query->bind_result($statementParams);";
eval($statment);
$query->store_result();
$affected = $query->num_rows;
// this request return me only ONE row
if ($affected == 1) {
while ($query->fetch()) {
foreach ($column as $key => $value) {
if ($key == "lookingFor") {
$row_tmb[$key] = formatLookingFor($value, $language, "");
} else {
$row_tmb[$key] = utf8_encode($value);
$row_tmb[$key] = $value;
}
}
$results[] = $row_tmb;
}
$query->free_result();
$query->close();
$profileData = $results[0];
// ... other code
}
This is return to my all column names and all 1 data row and I'm verry happy. So, I try to convert this code into PDO with new PDO code:
// good connection string without error in PDO code and the same query as you see up.
if ($query = $connection->prepare($sql)) {
$query->execute();
$metaResultsColNumber = $query->columnCount();
for ($i = 0; $i < $metaResultsColNumber; $i++) {
$metaResults[] = $query->getColumnMeta($i, ['name']);
}
var_dump($metaResults);
$fields = $metaResults->fetchColumn();
var_dump($fields);
$statementParams = '';
foreach ($fields as $field) {
if (empty($statementParams)) {
$statementParams.="\$column['" . $field->name . "']";
} else {
$statementParams.=", \$column['" . $field->name . "']";
}
}
$statment = "\$query->bind_result($statementParams);";
eval($statment);
$query->store_result();
$affected = $query->num_rows;
// TRACE
printf("SQL %d row(s) return", $affected);
if ($affected == 1) {
while ($query->fetch()) {
foreach ($column as $key => $value) {
if ($key == "lookingFor") {
$row_tmb[$key] = formatLookingFor($value, $language, "");
} else {
$row_tmb[$key] = utf8_encode($value);
}
}
$results[] = $row_tmb;
}
$query->free_result();
$query->close();
$profileData = $results[0];
And I can't obtain 1) the right column names 2) the data of the returning row
I try to read help into this site and PHP MySQL PDO documentation from many hours.
Do you look for something like that?
//Datastrucure
include("pdo_dbconnect.php");
$stmt = $db->prepare('select * from information_schema.columns where table_name = "' . $_SESSION[$fenster .'_tabelle'] . '" and table_schema = "' .$database.'"');
$stmt->execute();
$f = -1;
while ($data = $stmt->fetch()) {
$f += 1;
//pmsg($data['COLUMN_NAME'] . ' ' .$data['DATA_TYPE'] . ' ' . $data['CHARACTER_MAXIMUM_LENGTH']);
$_SESSION['_fieldName'][$f] = $data['COLUMN_NAME'];
$_SESSION['_fieldLenght'][$f] = $data['CHARACTER_MAXIMUM_LENGTH'];
$_SESSION['_extra'][$f] = $data['EXTRA'];
}
Need to find array, and then run a MYSQL SELECT where array values are present (or not present).
$symbol = "abc";
$sql = "SELECT * FROM around";
$results = $conn->query($sql);
foreach($results as $row) {
$stop = preg_replace("/[0-9]/", "", $row['tip']);
if ($stop == $symbol)
{$sword = $row['tip'];
}}
So we need $sword to serve as an array in the event that there are multiple outputs. After we have that array, we need to run a mysql query that shows only those that have $sword array.
$query = "
SELECT * FROM ms WHERE `big` = '$sword'";
$result = mysql_query( $query );
So then we can do something like:
while ( $row = mysql_fetch_assoc( $result ) ) {
echo '"time": "' . $row['time'] . '",'; }
Here's the code, converting $sword to an array and using it in your 2nd query:
$symbol = array("abc", "def", "ghi");
$sword = array();
$sql = "SELECT * FROM around";
$results = $conn->query($sql);
foreach($results as $row) {
$stop = preg_replace("/[0-9]/", "", $row['tip']);
if (in_array($stop, $symbol)) {
$sword[] = $row['tip'];
}
}
if ($sword) {
$in = '';
$sep = '';
foreach ($sword as $s) {
$in .= "$sep '$s'";
$sep = ',';
}
/* $in now contains a string like "'123abc123', '12abc12', '1abc1'" */
$query = "
SELECT * FROM ms WHERE `big` IN ($in)";
$result = mysql_query( $query );
while ( $row = mysql_fetch_assoc( $result ) ) {
echo '"time": "' . $row['time'] . '",';
}
}
Now I'm going to go wash my hands to get all that mysql_query off me... :-)