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>";
}
}
}
?>
Related
I post values to be added to a session array. If a value already exists in the array it should be removed. Both are not resulting in a change of the array.
<?php
session_start();
include_once($_SERVER['DOCUMENT_ROOT'] . '/v5/functions/connect_li.php');
//if (!isset($_session['cart'])) $_SESSION["cart"]= 9;
if (isset($_POST['myresort']) && !empty($_POST['myresort'])) {
$resorts = $_POST['myresort'];
$_SESSION['cart'][] = $resorts;
}
echo '<pre>';
print_r($_SESSION["cart"]);
if (isset($_POST['myresort'])) {
$key = array_search($_POST['myresort'], $_SESSION['cart']);
if ($key !== false) {
unset($_SESSION['cart'][$key]);
$_SESSION["cart"] = array_values($_SESSION["cart"]);
}
}
echo '</pre>';
if (!empty($_SESSION["cart"])) {
echo '<a href="/skirerport/">my resorts: ';
$_SESSION["cart"] = array_unique($_SESSION["cart"]);
$_SESSION["cart"] = array_filter($_SESSION["cart"], 'strlen');
$arr_as_string = implode(',', $_SESSION["cart"]);
$sql = "SELECT resort FROM sv_resorts WHERE res_id IN ($arr_as_string) ORDER BY resort LIMIT 10";
//echo $sql;
$res = mysqli_query($conn, $sql);
while ($ro = mysqli_fetch_array($res)) {
echo $ro['resort'] . " ";
}
print_r($_SESSION["cart"]);
echo "</a>";
}
?>
(Ignore this answer, it wont let me delete it via the app)
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 i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.
I have this function
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$arr = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
$set = "";
foreach($arr as $key => $v) {
$val = is_numeric($v) ? $v : "'" . $v . "'";
$set .= $key . '=' . $val . ', ';
}
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id']);
} else { echo "Done!"; }
echo $sql;
}
It outputs for example: UPDATE projects SET project_name='123', project_bold='123', project_content='123', WHERE id='12'
The last comma before where is preventing it from working. Is there a way of avoiding this? Im aware of the function implode, however I am not sure how to employ it in this situation.
Yes,
$sql = substr($sql,'',-1);
I would use
$sql = rtrim($sql, ',');
Either that or instead of appending to a string, append to an array and use implode.
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);
1) I want to save case 1 value to an array. Return this array and pass it to a function. The code become case 2, but no result come out, where is the problem?
2) In function display_urls, i want to echo both $url and $category. What should i do in IF condition or add another line of code?
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url."";
echo "".$category."";
}
}
echo "";
}
case 1: work fine
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$i=0;
echo "";
while( $row = oci_fetch_array($result) ){
$i++;
echo "";
echo "".$row['USERNAME']."";
echo "".$row['BM_URL']."";
echo "".$row['CATEGORY']."";
echo "";
}
echo "";
case 2:
$url_array = array();
while( $row2 = oci_fetch_array($result, OCI_BOTH)){
$i++;
$url_array[$count] = $row[0];
}
return $url_array;
I think you probably want something like this:
function display_urls($url_array)
{
echo "";
if (is_array($url_array) && count($url_array)>0)
{
foreach ($url_array as $url)
{
echo "".$url['BM_URL']."";
echo "".$url['CATEGORY']."";
}
}
echo "";
}
$result = oci_parse($conn, "select * from bookmark where username ='$username'");
if (!$result){ $err = oci_error(); exit; }
$r = oci_execute($result);
$url_array = array();
while( $row = oci_fetch_array($result, OCI_ASSOC)){
$url_array[] = $row;
}
display_urls($url_array);
This will store all the information on the URLs in $url_array with a lookup by column name.