Select word from string based on conditions - php

I'm currently attempting to select a specific word from a string based on surrounding conditions. Specifically, I'd like to select a word from a MySQL Query.
For example:
Select the word/words that is in surrounded by tildes (`): I am an `apple` -> apple;
SELECT `data` FROM `tableName` -> data -OR- {"data", "tableName"}; (I mostly need to output "data", but I can work around if I have to select everything in tildes.)
I have a query function that currently needs 2 parameters (to make it simpler to store database values in variables).
function MysqlQuery($query, $find)
{
$query = MysqlQueryWild($query);
$fetch = $query->fetch_array();
// Used to run a standard select query.
return $fetch[$find];
}
I'd like to chop it down to only needing one parameter, the query, and automatically selecting the column within the function with the above method.
Closest I got was this:
function MysqliQuery($query)
{
preg_match('"([^\\`]+)"', $query, $result);
$query = MysqlQueryWild($query);
$fetch = $query->fetch_array();
// Used to run a standard select query.
return $fetch[$result[0]];
}
But it selects the word "SELECT" which is NOT encased by tildes.

In sql you can use the keyword "Like" to find entries with specified conditions. % is used to represent 0-inf characters and _ represents 1 character. So for your example this is the select query you want.
SELECT 'data'
FROM 'table name'
WHERE 'column name' LIKE '`%`';
So for your case just use this query instead of trying to get all the words and manually find the ones surrounded by tildes

Related

SQL search can not return result if one word is right and another is wrong

In my website, there is a search box where a user gives input and search that word whether it is in the mySQL database or not.
My code :
$search_text = $_POST['srch-text'];
$sql = "SELECT * FROM search WHERE content LIKE '%$search_text%';";
$result = mysqli_query($dbcon, $sql);
$number_of_results = $result->num_rows;
It is working fine if anyone inputs two words which are existed in database.
Suppose anyone gives inputs "ABCD XYZ". Here ABCD exists in database but XYZ does not exist in database. Then it returns no result. I want to show the result of ABCD word.
You can use regular expressions. If you are using spaces to separate words, then you need to replace them with |:
SELECT *
FROM search
WHERE content REGEXP REPLACE(?, ' ', '|');
You should also be passing the string in using parameters, rather than munging the query string with user input. That is why this example uses ? as a placeholder for the parameter.
While you can use regex, I would use php's explode function to create an array, and then either do multiple sql queries or implode with % as the "glue".
You can split your string into two strings with space ' ' as separator
Here is a sql script which you easily convert into mysql
declare #s as varchar(100)
declare #s1 as varchar(100)
declare #s2 as varchar(100)
set #s='STRING1 STRING2'
declare #n as int
set #n=charindex(' ',#s)
if #n>0
begin
set #s1=substring(#s,1,#n-1)
set #s2=substring(#s,#n+1,len(#s))
end
select #s1 [mystring1],#s2[mystring2]
Then replace you query instead of
$sql = "SELECT * FROM search WHERE content LIKE '%$search_text%';";
by
$sql = "SELECT * FROM search WHERE content LIKE '%'+#string1+'%' or content LIKE '%'+#string1+'%'
Here is the equivalent mysql script
set #s='STRING1 STRING2';
set #n=LOCATE(' ',#s,1);
set #s1=substring(#s,1,#n-1);
set #s2=substring(#s,#n+1,LENGTH(#s));
select #s1 "mystring1",#s2"mystring2";

% (joker) does not work in my sql query with IN operator

I am reading out a database table, and excluding some rows with given values in a column.
But i cant get the query to get the right number for me. I suspect it still counts the kampanje_xxxxx rows. I use % to exclude.
$sql =
"SELECT *
FROM salg
WHERE
fnr='$fnr'
AND kategori NOT IN ('tilbehor', 'servicekontrakt', '%kampanje%')
AND dato BETWEEN '$fdato' AND '$tdato'"
;
$kjor = mysqli_query($connect, $sql);
$faste .= mysqli_num_rows($kjor). ", ";
The IN comparison operator takes list of values, it does not recognizes wildcards such as %. So your assumption that it still counts the kampanje_xxxxx rows is correct, since MySQL is actually searching for a litteral '%kampanje%' value.
You would need to create a separate LIKE condition to check the column againts the value that contains the wildcard. I believe that your query can be expressed as follows :
SELECT *
FROM salg
WHERE
fnr='$fnr'
AND kategori NOT IN ('tilbehor', 'servicekontrakt')
AND kategori NOT LIKE '%kampanje%'
AND dato BETWEEN '$fdato' AND '$tdato'
you should use OR not like and avoid wild char in IN set of values
"SELECT *
FROM salg
WHERE fnr='$fnr'
AND ( kategori NOT IN ('tilbehor', 'servicekontrakt')
OR NOT LIKE concat('%','kampanje','%') )
AND dato BETWEEN '$fdato' AND '$tdato'";
anyway you should avoid the use of php var in sql .. you are at risk for sqliject .. try take a look at ypour db driver for prepared statements and binding param
for see error eventually try show the exact erro message using
if (!$kjor) {
printf("Errormessage: %s\n", $connect->error);
}

Is it possible to use a $variable instead of 'row.table' in a mysql query?

For example:
$sql = "SELECT * FROM purch_inv WHERE '".$anyrow."'='".$anyrecord."'";
or
$sql = "SELECT * FROM '".$table."' WHERE 'rowabc'='".$anyrecord."'";
I have been trying this but it is not working, any ideas?
In php you could use variables in double quotes (ex.)
$name = 'John';
$var = "Hello $name!";
It shows: Hello John.
With single quotes (ex.)
$name = 'John';
$var = 'Hello $name!';
It shows: Hello $name.
Single-quotes mark a string literal.
But you want identfiers;
SELECT * FROM identifier1 WHERE identifier2='stringliteral'
a table name is an identifier. Identifiers
always can (and sometimes must) be wrapped in backticks.
SELECT x,y,z FROM `foo`
When I said a table name is an identifier, that wasn't entirely correct. In SELECT ... FROM foo foo is a name; it just so happens to be comprised of only one identifier, which is the table name.
There can be compound or multiple-part names, consisting of multiple identifiers connected via a dot between the parts. In that case you can (or must) wrap each single identifier in backticks; not the the whole name
SELECT x,y,z FROM `mydatabase`.`foo`
The fields you select (i.e. x,y and z in this case) are also names; so the same rules apply
SELECT `x`,`y`,`z` FROM `mydatabase`.`foo`
and again, in case you have multipart names you have to wrap each identifier individually in backticks, not the whole name
SELECT
`foo`.`x`,
`bar`.`x`,
`foo`.`y`,
`bar`.`z`
FROM
`foo`
JOIN
`bar`
ON
`foo`.`x`>`bar`.`y`
So, when do you use single quotes?
When you want a literal string in your query, like e.g.
SELECT x,y FROM foo WHERE y='abc'
this tells the MySQL parser that you want to compare the value of the field y to the string (literal) abc while
SELECT x,y FROM foo WHERE y=`abc`
would compare the value of the field y to the value of the field abc (which in my example doesn't exists and would therefore raise an error)
Full circle back to your question
$sql = "SELECT * FROM `$table` WHERE `rowabc`='$anyrecord'";
But please keep a good eye on http://docs.php.net/security.database.sql-injection regarding $anyrecord.
And make sure it is you (not the user) who is in control of $table.
yes you can
but you can't qoute the table name and column name
$sql="SELECT * FROM ".$table." WHERE rowabc='".$anyrecord."'";
the other example should be like this
$sql="SELECT * FROM purch_inv WHERE ".$anyrow."='".$anyrecord."'";
Obviously you need to think about SQL injection with the variables getting passed into your select query! So because table and column names cannot be replaced by parameters in PDO, you could use a function to create a whitelist of table names to pass into your query, then use a function with PDO to execute the statement:
$myWhitelist = array('table1', ...)
$myTable= array_intersect_keys($table1, array_flip($whitelist));
So now $table1 is safe to pass into your select function:
function select($conn, $table1, $someColumn) {
$myvar = $conn->prepare("SELECT FROM ".$table1." WHERE id = :someColumn");
$myvar->bindParam(":someColumn", $someColumn, PDO::PARAM_INT);
$myvar->execute();
if ($myvar->rowCount() > 0) {
return true;
} else {
return false;
}
}

passing variable with multiple values seperated by comma to sql statement through PHP

I've looked all over the interwebs, and cannot find that simple answer I'm looking for - possibly because it doesn't exist, but.. possibly because I don't know the correct terms to search for.
ok, so, i've got a variable - it's actaully a key value pair in an array that i'm passing into my function. the key is args[comments_mentioned] and the value is dynamically generated for me - it's ALWAYS going to be number, separated by commas (i.e. 1,2,3,4,5)
so, just to be super clear:
$args[comments_mentioned] == "1,2,3,4"; //could be any amount of number, not just 1,2,3,4,5
i'd like to pass this into a sql statement as a variable to use in an "IN" clause, like so:
$sr_sql = <<<SQL
SELECT *
FROM $wpdb->commentmeta
WHERE meta_value = %s
AND comment_ID in ($args[comments_mentioned])
ORDER BY meta_id DESC
SQL;
Then, Prepare it using the wordpress prepare and get results
$sr_query = $wpdb->prepare( $sr_sql, $args[user_id]) );
//receive the correct sql statement, and plug 'er in.
$sr_comment_rows = $wpdb->get_results($sr_query);
and run my foreach loop:
foreach ($sr_comment_rows as $sr_comment) {
$sResults .= 'do something with $sr_comment';
}
now, i realize the code above won't work - i can't just pass the variable in there like that. BUT, i can't pass it as a string (%s), because it wraps it in '1,2,3,45', and so it looks for the entire string, and not each number. I can't pass it as an int (%d), because of the commas...
In other posts, they mentioned create a temp table or variable, but, i'm not sure if that's the correct way to do it in mysql, or how to reference it once I do.
so, how do I do this? preference for actual code that works ;)
Thank you for reading and helping out!
One option, if you cannot normalize your data, is to enclose your string in commas such that it be ",1,2,3,4," and then you could do:
AND LOCATE( CONCAT(',',comment_ID,',') , ($args[comments_mentioned]) )
which will match if it finds a eg. ',3,' in ',1,2,3,4,' (Using 3 as an example)
I believe this should be enough:
$params = $args[comments_mentioned];
$table = $wpdb->commentmeta;
$sr_sql = "
SELECT *
FROM $table
WHERE meta_value = %s
AND comment_ID in ($params)
ORDER BY meta_id DESC
";
It will be result something like:
SELECT *
FROM table_on_variable
WHERE meta_value = %s
AND comment_ID in (1,2,3,4)
ORDER BY meta_id DESC
If your mainly issue is regarding the in clause, so you will not have problems if you use double quotes and single variable as illustrated above.

How do i select multiple rows which match the value of an item in an array?

I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:
$id = array(1,4,7,3,11,120); // The array containing the ids
$query = mysql_query("SELECT *
FROM posts
WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`
I think you want the IN clause:
$idList = implode(",", $id);
SELECT *
FROM posts
WHERE id IN ( $idList );
The implode() function will turn your array of numbers into a comma-separated string of those same values. When you use it as part of an IN clause, it tells the database to use those values as a lookup table to match id against.
Standard Disclaimer/Warning:
As with any SQL query, you really shouldn't be directly concatenating variables into the query string. You're just opening yourself up to SQL injection. Use prepared/parameterized statements instead.
Use PHP's implode function to convert the array into a comma separated value string.
Then, you can use the SQL IN clause to run a single SQL statement containing the values associated with the ids you captured from PHP:
$id = array(1,4,7,3,11,120);
$csv = implode(',', $id);
$query = sprintf("SELECT *
FROM posts
WHERE id IN (%s)",
mysql_real_escape_string($csv));
$result = mysql_query($query)
I omitted the single quotes because they aren't necessary when dealing with numeric values in SQL. If the id values were strings, each would have to be encapsulated inside of single quotes.
What you want is SQL's IN clause.
SELECT * FROM posts WHERE id IN (1, 4, 7, 11, 120)
In PHP, you'll probably want something like:
$query = mysql_query(sprintf("SELECT * FROM posts WHERE id IN (%s)", implode(',', $id)));
Obviously, that's assuming you know you have integer values for $id, and that the values for $id didn't come from the user (that is, they should be sanitized). To be safe, you really ought to do something like:
$ids = implode(',', array_map('mysql_real_escape_string', $id));
$query = mysql_query("SELECT * FROM posts WHERE id IN ($ids)");
And if $id is dynamically generated, don't forget to put something in that IN clause, because SELECT * FROM foo WHERE bar IN () will give you an error. I generally make sure to set my IN-clause variables to 0, since IN (0) is good, and primary keys are pretty much never 0.

Categories