How to get the row of the matched statement? - php

I am grabbing a feed from API and and here I want to get the row that starts with ,,[[,2 . Please help me how can I do that ?

The RegExp that I came up with in PHP is:
$s = ',,[[,2thesecretoflife';
$r = preg_match('/^,,\\[\\[,2/', $s);
if ($r) {
echo 'works';
}
Basically, you have to double escape the [s to get them to be interpreted properly. I'm sure that whatever language you are using would be similar.

Related

Copy multiple SQL rows to array, then compare array to another PHP

I have a web page that displays a list of names that change throughout the day. I also have a database that contains a list of all of these names.
I need to somehow run a search on the names that are displayed on the web page at any specific time, then match these against the names that are contained in the db. This is sort of a reverse lookup.
The names that are unable to be found on the web page need to be displayed.
How do I go about doing this?
I am attempting to try parsing the names contained in the db rows to an array and the names on the web page to another array then comparing the two arrays.
I have managed to parse them correctly but there is an issue when I try comparing them.
Please point me in the right direction :)
<?php
$a = file_get_contents("https://testpage.com/pbx_info2.php");
#find all the names that are contained within '[' and ']'
preg_match_all('^\[(.*?)\]^', $a, $matches);
#output all the names into an array
$output = $matches[0];
#remove the '[' and ']' characters and print the contents of the array.
foreach($output as $u) {
$u = str_replace ('[', '', $u);
$u = str_replace (']', '', $u);
print $u;
echo "<br>";
}
$con=mysqli_connect("localhost","test_user","test_pass","test_teaams");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "<br>Connected!<br>";
}
$sql="SELECT * FROM test_table";
if ($result=mysqli_query($con,$sql))
{
while ($row=mysqli_fetch_row($result))
{
printf (" ".$row[0],$row[1]);
}
// Free result set
$people[0] = mysqli_free_result($result);
$peep = $people[0];
}
$missing = array_intersect($output, $people);
printf ($missing);
mysqli_close($con);
?>
If you want to remove the square brackets from your array elements you need to work with references in the foreach loop:
#remove the '[' and ']' characters and print the contents of the array.
foreach($output as &$u) {
$u = str_replace ('[', '', $u);
$u = str_replace (']', '', $u);
print $u;
echo "<br>";
}
The &$u does the job. Otherwise you will not have changed $u "in place" within its $output array but instead will have created a new $u variable which will be overwritten every time in the loop.
Instead of comparing the returned results in PHP you could filter the table rows already in the database by creating a suitable WHERE condition for your SELECT statement:
$where=count($output)?"WHERE usrname NOT IN ('".join("','",$output)).')":'';
This will construct a WHERE clause only when there are userids to be matched. And lateron apply it in
$sql="SELECT usrname,col1,col2,col3 FROM test_table $where";
// it is NOT a good idea to use * in SELECT statements since
// a table structure might change over time ...
assuming that usrname is the column with the user names. The returned rows should be the ones you want: entries in the database that do not appear on the website.
Edit:
You can avoid the first problem entirely if you work with a better regular expression:
preg_match_all('^(?<=\[)(.*?)(?=\])^', $a, $matches);
The (?<=\[) and (?=\]) are called look-behind and look-ahead patterns and are not part of the matched strings.
see here: https://regex101.com/r/qK4yQ0/1

php - get character count between two points encased in quotes

Ok this is going to be weird but I need it
I am trying to get the character count for a huge line of code between some particular quotes ". Basically I need to be able to get everything between the 3rd quote in the beginning and the 5th quote at the end.
So here is an example
a:2:{s:10:"categories";s:5758:"...........";s:5:"posts";s:6:"a:0:{}";}
I need to know what the character count is of all the periods. There is actually code in place of those periods.
Since there are 11 periods then my character count will be 11. The only consistent thing is the quotes in this so I need to base off that.
Any help would be awesome.
Here is my code. I am basically creating the code and adding some custom labels. I tried serializing the code first before I unserialize it but that didn't seem to work.
<?
$thisisit .= 'a:2:{s:10:"categories";s:5481:"a:40:{';
include('connect.php');
$sql = "SELECT * FROM wp_terms ORDER BY term_id ASC LIMIT 40";
$result = mysql_query($sql);
$count = 0;
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$charactercount = strlen($name);
$term_id = $row['term_id'];
$thisisit .= 'i:'.$count.';a:2:{s:11:"filter_name";s:20:"add_keyword_category";s:11:"filter_args";a:7:{s:12:"filter_value";s:'.$charactercount.':"'.strtolower($name).'";s:19:"filter_search_title";s:1:"1";s:21:"filter_search_excerpt";i:0;s:21:"filter_search_content";s:1:"1";s:21:"faf_filter_categories";a:1:{i:4;s:3:"'.$term_id.'";}s:17:"filter_match_word";i:0;s:17:"filter_match_case";i:0;}}';
//echo "<br><br>";
$count++;
}
$thisisit .= '}";s:5:"posts";s:6:"a:0:{}";}';
$array = unserialize($thisisit);
echo strlen($array['categories']);
?>
Actually this data looks serialized. The correct solution would be to use php function unserialize.
Then, given your structure, to know the length of that element:
strlen(unserialize($data)['categories']);
If you run old php, you need to store the result in a temporary variable:
$array = unserialize($data);
echo strlen($array['categories']);
If your serialized data is corrupted (as in "not received from proper execution of serialize"), as it seems from your example, we can return to your original task:
get everything between the 3rd quote in the beginning and the 5th quote at the end
The simplest way to achieve that is:
implode("'", array_slice(explode("'", $data), 3, -5));

PHP Query Not Understanding Integer

Here's my code:
function display_name1($s){
global $db;
$query1 = 'SELECT Name From Drink where P_Key = $s';
$r = $db->prepare($query1);
$r->execute();
$result = $r->fetchColumn();
return $result;
}
$s contains the result returned from the P_Key, an auto incremented column. I want to be able to give the query the P_Key and it will return whatever variable from that row I want. For some reason, this isn't working. It returns nothing. Now if I return $s, then it does display the numbers like it should, so the problem isn't with the $s variable itself. If I take the $s out of the query, and replace it with a number, then it returns the name of the drink just like it should, so the problem isn't with the database or the query. The problem seems to be that $s is being interpreted incorrectly.
I've tried converting it to an integer ahead of putting it into the query, no dice. Any ideas?
Try to use double quotes.Single quote didn't interpret the variables."SELECT Name From Drink where P_Key = $s"
Reference: PHP String Parsing
use like this
"SELECT Name From Drink where P_Key = ".$s.""
you can find difference using echo $query1

while loop not working for acessing sql records

I am passing a string to this file -txtname- (string separated by spaces) and saparate each word and then pass it to the function subtoken() that should fetch the corresponding words from the database, having two attributes-rootwords and example,but subtoken() function executes only once and exits.
$counter=0;
$string = $_REQUEST['txtname'];
$token = strtok($string, ' ');
while ($token != false)
{echo $counter;
subtoken($token,$counter);
$counter++;
$token = strtok(' ');
}
function subtoken($fname,$counter)
{
$row ="";
$result="";
$result = mysql_query('SELECT * FROM hindi WHERE rootwords LIKE \'%:'.$fname.':%\'' );
while($row = mysql_fetch_array($result))
{
$temp=$row['rootwords'];
$token2 = strtok($temp, ':');
echo $token2 ;
while($token2!=false)
{
echo $token2."<br/>" ;
$token2=strtok(':');
}
}
}
mysql_close($con);
The double usage of strtok will prevent the "main" loop to properly process all tokens from the original $string. You simply can't have more than one "open" strtok use at the same time.
Original suspect was your query, that it just doesn't select anything. Try printing the SQL statement, then executing that statement directly (e.g. via phpmyadmin)
// insert this line:
echo(
'SELECT * FROM hindi '.
'WHERE rootwords LIKE \'%:'.$fname.':%\'');
// just before the actual query execution
$result = mysql_query(
'SELECT * FROM hindi '.
'WHERE rootwords LIKE \'%:'.$fname.':%\'' );
From my experience, echo'ing as much data as possible early on while debugging is one of the best tools to easily spot errors.
See also: http://nl2.php.net/mysql_fetch_array
mysql_fetch_array needs a second parameter to work correctly.
Replace mysql_fetch_array with mysql_fetch_row. Or mysql_fetch_assoc if you want to reference to the columns by name.
May be you have some error/warning? Is error_reporting set to E_ALL and display_errors to "On"?
It seems that strtok() has only one pointer. So, when you ended with it in function, you need to reinitialise $token = strtok($string, ' ');? dut I am not sure. I think it would be better if you used explode() function.

PHP script with MySQL statement with single quote

I'm learning PHP,MySQL and came across this function today
function get_director($director_id) {
global $db;
$query = 'SELECT
people_fullname
FROM
people
WHERE
people_id = ' . $director_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
extract($row);
return $people_fullname;
}
I understand what functions are and I've created a few while learning PHP.But this one is a bit more complicated.I can't understand the
WHERE people_id = ' . $director_id
I guess the single quote ends the MySQL statement? And then it is concatenated with the argument?
Yes you are right, the single quotes end the sql string and concatenate with the supplied argument. Same case if you want to print the value out.
echo 'This is the director ID :'.$director_id;
I wouldn't call this operator an "SQL statement". And wouldn't say it is "closed" either.
For PHP it's just a string with no particular meaning.
And the quote ends this string literal, not SQL statement.
Strictly speaking here is just a concatenation, a string literal with a variable.
Having a whole complete SQL statement as a result.
The .(dot) is used for concatenation in php.
If you pass 32 to $director_id then the final query will be
select people_name from people where people_id = 32
If you pass 43 to $director_id then the final query will be
select people_name from people where people_id = 43
Means the .(dot) is used for appending the value of $director_id to the string in single quotes.
The final query will be passed to mysql. Using .(dot) is just a method in php to generate the final query that we want to execute in mysql.
I guess the single quote ends the MySQL statement?And then it is concatenated with the argument? Please help me out.
That is correct.
http://php.net/manual/en/language.operators.string.php
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
EDIT: The meaning of the WHERE clause is best explained by the psuedo explanation of what the entire statement does.
SELECT everyone's full name WHERE their people_id is EQUAL TO some value passed into the function.
However, you are way over your head if you are evaluating these things and don't understand the basic SQL. I recommend you read the entire Tiztag PHP/MySQL tutorial.
http://www.tizag.com/mysqlTutorial/

Categories