Explode a String and Check Database for Duplicate - php

How can I take a string business, jquery, css and explode that string and check a mySQL database to see if each one of the single words is already inside a database entry?
Thanks,
Drummer392

$string = "business, jquery, css";
$exploded = explode(",", $string);
$result = /* database select query */
foreach ($exploded as $value) {
// $value contains the value being processed
// compare $result to $value and do what's needed
}
PHP Manual: explode()
Hope that give you an idea as to what you need to do.
Edit: thanks to Chris for the suggestion of doing the database query first

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $conn);
$string = "business, query, css";
$array = explode(", ", $string);
foreach($array as $str){
$result = mysql_query("SELECT * FROM tableName WHERE columnName='$str'", $conn);
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
//found
else
//not found
}

Use PHP's explode function with a ", " delimiter, assigning to a new array variable.
I would improve upon the previous answer, I feel it would be better to use the SELECT query outside of the foreach loop. Then you'll avoid executing the same query 3 times.
$result = /* database select query */
foreach ($exploded as $value) {
// compare $result to $value and do what's needed
}

Related

Split out a string and search'em in sql

I'd like to split a string into array and search every split array in query that'll pull related answer from database.
Here is my code. But it's not working....
$str=$_POST['search'];
$a=preg_split("/[\s]/", $str,);
foreach ($a as $search) {
$sql = "SELECT answer FROM query_tbl WHERE (q1 like \"$search%\" OR q2 LIKE
\"$search%\" OR q3 LIKE \"$search%\" OR q4 LIKE \"$search%\")";
$record = mysqli_query($link, $sql);
$rows=mysqli_fetch_assoc($record);
echo json_encode(array('ans'=>$rows['answer']));
}
Imagine 1$str=" this makes no sense ";1 then the query will be searched by "this", "makes", "no", "sense". If the sub-string matched with answer lies in query then it'll be printed.
There are a couple of issues here. (I am assuming this is PHP)
First, I would use this syntax for your string concatenation:
"SELECT answer FROM query_tbl WHERE (q1 like '".$search."%'.OR..."
Secondly, check out the implode function fro the "OR"s and use the loop to just add the dynamic part to the static string http://php.net/manual/en/function.implode.php :
$str=$_POST['search'];
$a=preg_split("/[\s]/", $str);
var_dump($a);
foreach($a as $key => $word) {
$a[$key] = "q1 like '".$word."%'";
}
$ORS = implode(" OR ", $a);
$sql = "SELECT answer FROM query_tbl WHERE ".$ORS.";";
$record = mysqli_query($link, $sql);
$rows=mysqli_fetch_assoc($record);
echo json_encode(array('ans'=>$rows['answer']));
}

How to extract comma separated column values from database using php

In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php

PHP Array to string conversion, mysql_fetch_assoc() expects parameter [duplicate]

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 8 years ago.
Can someone please help me with my code, I can't get it to work.
I have an html input form where I type for example "This is a sample".
(data is saved in $_POST['Begriff'])
I want to achive a simple translation, so that the table "drinks" in column "English" is checked for existence of every single word from my input sample sentence and output if found every entry from the corresponding row in one line.
Right now I have two problems:
As soon as I add " where English in $wert" to the select statement I get:
Notice: Array to string conversion in nachlesen.php on line 34
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given
Second Problem: How to I put the sentence together again from the returned results?
(Right now I get the output for every found word below each other, instead of one line)
Here is my code:
if ( $_POST['Begriff'] <> "")
{
$wert = explode(' ',$_POST['Begriff']);
$select = mysql_query ("SELECT * FROM drinks where English in $wert");
while ( $row = mysql_fetch_assoc($select))
{
echo ("$row[German] <br>");
echo ("$row[English]<br>");
}
}
Thanks in Advance, Daniel
<?php
// premise: the user input in $_POST['Begriff'] is a string like 'This is a sample'
//first split it into single words
// preg_split: \s+ -> one or more whitespaces , PREG_SPLIT_NO_EMPTY -> no "empty" words
// e.g. " Mary had a little lamb" -> array('Mary','had','a','little','lamb')
$words = preg_split('!\s+!', $_POST['Begriff'], -1, PREG_SPLIT_NO_EMPTY);
// now encode each string so that it can be used
// safely as a string-literal within your sql query
// see: sql injection
// this should be:
// $words = array_map(function($e) use($mysql) { return mysql_real_escape_string($e, $mysql); }, $words);
// but apparently you're not storing the resource that is returned by mysql_connect
// mysql_real_escape_string() is applied to each single element in $words
// e.g. array("it's", "been") -> array("it\\'s", "been")
$words = array_map('mysql_real_escape_string', $words);
// now put the string literals into your query
// format: ... IN ('x','y','z')
// join(",", $words) gives you x,y,z
// join("','", $words) gives you x','y','z
// i.e. the first and the last ' has to be added "manually"
// keep in mind that for an empty array $words this will produce WHERE ... IN ('')
// better test that before even trying to build the query
$query = sprintf("
SELECT
German,English
FROM
drinks
WHERE
English IN ('%s')
", join("','", $words));
// send the query to the MySQL server
// should be: $result = mysql_query($query, $mysql);
$result = mysql_query($query);
// database query -> failure is always an option
if ( !$result ) {
// add error handling here
}
else {
// in case there is not a single match in the database
// your script would print ...nothing
// I don't like that - but that debatable
// anway: wrapped in a fieldset
echo '<fieldset><legend>results:</legends>';
while( false!==($row=mysql_fetch_array($result, MYSQL_FETCH_ASSOC)) ) {
printf('%s<br />%s<br />',
// just like on the input-side you had to worry about
// sql injections
// on the output side you want to avoid
// that characters from the database can break your html structure
htmlentities($row['German']),
htmlentities($row['English'])
);
}
echo '</fieldset>';
}
(script is untested)
why don't you try implode() and convert your array to string??
if ( $_POST['Begriff'] <> "")
{
//you'l have to replace all "spaces with ',' "
$pattern = '/\s*,\s*/';
$replace = "','";
$wert = preg_replace($pattern, $replace, $_POST['Begriff']);
$select = mysql_query ("SELECT * FROM drinks where English in ('$wert')");
while ( $row = mysql_fetch_assoc($select))
{
echo ("$row[German] <br>");
echo ("$row[English]<br>");
}
}
ANOTHER SOLUTION (TO PREVENT SQL INJECTION)
if ( $_POST['Begriff'] <> "")
{
//replace multiple spaces
$str1 = preg_replace( "/\s+/", " ", $_POST['Begriff'] );
//convert to array, separated by space
$arr=explode(" ",$str1);
$safe_params=array();
foreach($arr as $param){
$safe_params[]=mysql_real_escape_string($param);
}
$wert=implode("','",$safe_params);
$select = mysql_query ("SELECT * FROM drinks where English in ('$wert')");
while ( $row = mysql_fetch_assoc($select))
{
echo ("$row[German] <br>");
echo ("$row[English]<br>");
}
}
EDIT
Processing query output according to language
$german_words=array();
while ( $row = mysql_fetch_assoc($select))
{
$german_words[$row['English']]=$row['Gernam'];
}
//$str1 is having english string
echo "English: ".$str1."<br/>";
echo "German : ";
//$arr is having array of words of $str1
foreach($arr as $eng_word){
echo $german_words[$eng_word]." ";
}
"SELECT * FROM drinks where English in ('". implode("','", $wert) . "')"
EDIT: SQL Injection safe query:
$dsn = 'mysql:dbname=' . $settings['dbname'] . ';host=' . $settings['dbhost'];
$pdo = new PDO($dsn, $settings['dbuser'], $settings['dbpass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if ( $_POST['Begriff'] <> "")
{
$wert = explode(' ',$_POST['Begriff']);
$placeholders = implode(',', array_fill(0, count($wert), '?'));
$sth = $pdo->prepare("SELECT * FROM drinks WHERE English in ({$placeholders})");
$sth->execute($wert);
$rows = $sth->fetchAll();
foreach($rows as $row) {
print_r( $row );
}
}

How to order this array to High to Low? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to sort the results of this code?
I have made this code which allows a user to type in a search bar a question. This code then takes that question and looks for watching words with questions in my database. It then counts the number of matching words for each question. Once done it then displays the top 4 best matched questions depending on how many words match.
However at the moment it displays these matches from lowest word match to highest word match (low-to-high) and I was it the other way around so that it displays the best match first (high-to-low). How do I do this in this code?
<?php
include("config.php");
$search_term = filter_var($_GET["s"], FILTER_SANITIZE_STRING); //User enetered data
$search_term = str_replace ("?", "", $search_term); //remove any question marks from string
$array = explode(" ", $search_term); //Seperate user enterd data
foreach ($array as $key=>$word) {
$array[$key] = " title LIKE '%".$word."%' "; //creates condition for MySQL query
}
$q = "SELECT * FROM posts WHERE " . implode(' OR ', $array); //Query to select data with word matches
$r = mysql_query($q);
$count = 0; //counter to limit results shown
while($row = mysql_fetch_assoc($r)){
$thetitle = $row['title']; //result from query
$thetitle = str_replace ("?", "", $thetitle); //remove any question marks from string
$title_array[] = $thetitle; //creating array for query results
$newarray = explode(" ", $search_term); //Seperate user enterd data again
foreach($title_array as $key => $value) {
$thenewarray = explode(" ", $value); //Seperate each result from query
$wordmatch = array_diff_key($thenewarray, array_flip($newarray));
$result = array_intersect($newarray, $wordmatch);
$matchingwords = count($result); //Count the number of matching words from user entered data and the database query
}
if(mysql_num_rows($r)==0)//no result found{
echo "<div id='search-status'>No result found!</div>";
}
else //result found
{
echo "<ul>";
$title = $row['title'];
if ($matchingwords >= 4){
?>
<li><a href='<?php echo $row['url']; ?>'><?php echo $title ?><i> No. matching words: <?php echo $matchingwords; ?></i></a></li>
<?php
$count++;
if ($count == 5) {break;
}
}else{
}
}
echo "</ul>";
}
?>
If you have saved you data in an array you can simply reverse it by using http://www.php.net/manual/en/function.array-reverse.php
Otherwise there are some sort functions
http://php.net/manual/en/function.sort.php
I think you have problem in sorting an array.
If you have an array, sorting is not a matter.
Having different types of sorting found in php.
arsort()
Sort an array in reverse order and maintain index association
http://www.php.net/manual/en/function.asort.php
You can use this array function or let me know your questions briefly.
you can write a own filter function
// sorts an array by direction
function arr_sort($arr, $index, $direction='asc')
{
$i_tab = array();
foreach ($arr as $key => $ele)
{
$i_tab[$key] = $arr[$key][$index];
}
$sort = 'asort';
if (strtolower($direction) == 'desc')
{
$sort = 'arsort';
}
$sort($i_tab);
$n_ar = array();
foreach ($i_tab as $key => $ele)
{
array_push($n_ar, $arr[$key]);
}
return($n_ar);
}
for example you have an array $arr = array('key' => 'value', 'key2' => 'value');
you can now sort by key2 asc with
$arr = arr_sort($old_arr, 'key2', 'desc');
so you can put the total count of matching words into your array as a node for any entry and filter it by it descending
note this requires Mysql version 4+
A fulltext sql query returns values based on relevance.
Example:
SELECT *, MATCH (title)
AGAINST ('$search_term' IN NATURAL LANGUAGE MODE) AS score
FROM posts;
This is how you would implement it
$q = "SELECT *,MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) AS relevancy FROM
posts WHERE MATCH (title) AGAINST ('$search_term' IN BOOLEAN MODE) ORDER BY
relevancy DESC";
This will return the posts in order by relevancy. May need to remove the '' around $search_term but you can figure that out with testing.
Please read up on Fulltext sql queries and the match() function. It is all clearly documented.

Picking numbers in an order

I had a task to slide images from a mysql database using jquery slide and not the animation scripts. The slide is supposed to show at least the most recent ten images that was uploaded. With that I first of all wrote a random query
mysql_query("select * from tblname order by rand() limit 1);
But as expected, it picks the images at random irrespective of when it was posted and of course it wasn't the most recent ten. After some thought I now had to first run a query to get the most recent ten
mysql_query("select * from tblname order by ID limit 10);
while($row=mysql_fetch_array($sql){
$slideid=$slideid.",".$row['recordid'];
}
this of course results to a variable of this order
$var="23,22,24,34,27,78,56,87,98,55";
I tried handling it like an array but it wasn't giving any positive result, hence I had an issue of how to pick this numbers and use it for the slide
$myArr=explode(',',$var);
sort($myArr);
for($i=0;$i<count($myArr);$i++)
{
echo $myArr[$i];
}
Edit: For better efficiency use:
$myArr=explode(',',$var);
sort($myArr);
foreach ($myArr as $val)
{
echo $val;
// Or do whatever else you want with each one.
}
Edit 2: See comments below on efficiency vs for loops vs unexpected results. :)
Based on your comments I will offer my 2p into the mix
this is what I did $slideid="23,22,24,34,27,78,56,87,98,55"; $arr =
explode(',',$slideid); foreach ($arr as $val) { //lets get the
variables from the form post $rs = mysql_query("SELECT * FROM tblname
WHERE id='$val'") or die(mysql_error());
while($row=mysql_fetch_array($rs)){ echo "<img src='image/$image'>"; }
} the images are displayed one by one using jquery slide
Now I think we are wasting time dealing with exploding this variable because mysql has the nifty IN() function (possibly in other db's I don't know)
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid})") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}
I hope this helps
$var="23,22,24,34,27,78,56,87,98,55";
$arr = explode(',',$var);
foreach ($arr as $val) {
// work with $val
}
explode splits the string to an array
1) Explode the string into an array, splitting on the comma.
2) You didn't say whether you wanted to re-order the numbers into numerical order, or process them in the order they're already in. If the former, sort the array with sort($arr);
3) Loop over the array in sequence and do something with each number
$str = '1,2,3,4,5,6';
$arr = explode(',', $str);
foreach($arr as $num) echo $num.'<br />';
Note if there is any change of spaces after commas, a better choice would be preg_split rather than explode, as this is more dynamic.
$arr = preg_split('/, ?/', $str);
You can achieve this using php explode function
$pieces = explode(",", $var);
echo $pieces[0]; // piece1
echo $pieces1; // piece2
.
.
.
echo $pieces[n]; // piece n
I think you need to get result of order with respect to order of variable here
$slideid = "23,22,24,34,27,78,56,87,98,55";
$rs = mysql_query("SELECT * FROM tblname WHERE id IN({$slideid}) ORDER BY FIELD(id, {$slideid}) ") or die(mysql_error());
while ($row = mysql_fetch_assoc($rs))
{
echo "<img src='image/{$row['image']}' />";
}

Categories