Copy multiple SQL rows to array, then compare array to another PHP - 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

Related

Compare a table column between MYSQL and SQL Server to get the difference

I need to compare a table column coming from two different type of databases(MYSQL and SQL Server) in php.
For the background the table column that i need to compare doesn't have the same values so i am converting them first for proper comparison e.g value in MYSQL is BN014 which is equivalent to BN00000014 in SQl Server (just extra 4 to 5 zeros after first two characters). I am using the following function for the required conversion, this part seems to be working fine:
function convertWR($wr)
{
$mysqli=$this->con;
$wr_number = $wr;
$prod_zeros='';
$p_cat=substr($wr_number,0,2);
$p_num=substr($wr_number,2,strlen($wr_number)-2);
$p_num_len=strlen($p_num);
$ctrl=8;
while ($ctrl>$p_num_len){
$prod_zeros.="0";
$ctrl--;
}
$converted_id=$p_cat.$prod_zeros.$p_num;
return $converted_id;
}
For the comparison part i am storing the results from both databases in separate arrays named $wr_from_mssql and $wr_from_mysql respectively, then comparing them using the function array_diff():
function compareData()
{
//SQL Server data
$mssql=$this->mssql;
if($mssql)
{
//echo "connected";
if(($result = sqlsrv_query($mssql,"SELECT [ItemId] FROM [dbo].[Item]")) !== false)
{
$count_mssql=1;
$wr_from_mssql=array();
while( $obj = sqlsrv_fetch_array( $result ))
{
$clean_itemid=$string = str_replace(' ', '', $obj['ItemId']);
$wr_from_mssql[]=$clean_itemid;
$count_mssql++;
}
}
}else {
die(print_r(sqlsrv_errors(), true));
}
//-----------------------------------------------------------------------//
//MYSQL data
$mysqli=$this->con;
$count_mysql=1;
$wr_from_mysql=array();
$sql="SELECT WR FROM products";
$result= mysqli_query($mysqli,$sql);
while ($row = mysqli_fetch_array($result)){
//for the required conversion e.g BN014 to BN00000014
$wr= $this->dynacomWR($row['WR']);
$clean_wr=$string = str_replace(' ', '', $wr);
$wr_from_mysql[]=$clean_wr;
$count_mysql++;
}
//----------------------------------------------------------------------//
//To get the difference
$result=array_diff($wr_from_mssql,$wr_from_mysql);
$count_diff=1;
foreach($result as $diff)
{
echo $count_diff.") ".$diff."</br>";
$count_diff++;
}
mysqli_close($mysqli);
$result2=array_diff($result,$wr_from_mysql);
mysqli_close($mysqli);
}
However i am not getting the expected results, I am still getting 3000+ values that exists in both tables. I am expecting around 7000 results while getting 10,000++ .
There are no white spaces or regular spaces(though i still tried removing them) that could affect this comparison as we do clean the strings before inserting them to our tables.
Any idea what could be going wrong, any other possible method for this type of comparison? need it for a report so cannot use the free tools available.
Probably not the best approach as suggested by #GordonLinoff , but I was able to get the desired results :) by creating a temporary table with the converted values and then using the above code, off course with some modifications for mysql query to compare the column values between the new temporary table and the SQL Server table.
I was unable to use the linked server due to a network issue which i will resolve in future. Have some deadlines to meet.

Creating array of fields then looping through set in PHP

I'd like to simplify how my app builds a query and loops through the results. Most of the actual code works, except that PHP does not display all of the results fetched from my query.
PREFACE: example code ahead, do not use in production.
First I build the query.
$arr_fields = array('color', 'number', 'size');
$select_fields = implode(', ', $arr_fields);
$q = "SELECT $select_fields FROM supplychain";
Now I execute the query then loop through the result set.
Pro tip: don't use this code for anything important - it's for demo purposes only.
echo "<table>";
$res = doQuery($q);
// create report body
foreach($res as $r)
{
// set values from array of field names
$row_fields = '';
foreach ($arr_fields as $f)
{
// set current $arr_field value inside a table cell...
$row_fields.= "<td>$r[$f]</td>";
}
// display the row
echo "<tr>$row_fields</tr>";
}
echo "</table>";
The first database value from $arr_fields (color) is output as expected, the rest are not.
The assembled query issued at a MySQL console shows values for color, number and size. There aren't any SQL errors generated by the script.
Why is PHP displaying the first field's value but skipping the other two?
The issue turned out to be a space before each of the fieldnames in my array (not shown in the example above).
The field array actually was
$arr_fields = array('color', ' number', ' size');
Once I removed the spaces, values showed up as usual. Thanks for Norbert for helping point me in the right direction via additional testing.
Change this line:
$row_fields.= "<td>$r[$f]</td>";
to:
$row_fields.= "<td>".$r[$f]."</td>";

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));

How do I echo the contents of a MySQL table field?

I seem to be having trouble understanding the concept of how to properly use the information in a MySQL database using PHP/MySQLi. As I understand it, you generate a variable representing the connection object:
$connectionObject = mysqli_connect('serverString', 'userString', 'passString', 'databaseString');
then, generate a variable representing the query string you want to use:
$queryString = "SELECT rowName FROM tableName";
then, generate a variable representing the result object returned from a successful query:
$resultObject = mysqli_query($connectionObject, $queryString);
then, you use the fetch_assoc() function to generate an array from the result object and assign it to a variable:
$resultArray = myqli_fetch_assoc($resultObject);
then, you can use a while loop to (I have trouble with this one) to sort through the array and use the content of the row somehow:
while ($resultArray) {
echo $resultArray["rowName"];
}
Do I have this concept the wrong way, somehow, because its just not working for me, even to output the text content of a text-based CHAR(10) field with the contents of no more than: "BLAH".
The need to loop through the array to pick out the array item by name in the end anyway seems moot to me to begin with, but no matter where I look, I find the same concept.
My script code, minus a few key details, is:
if ($connectionObject=mysqli_connect("host0", "username0", "password0", "mysqldatabase0")) {
echo "Con";
}
if ($queryString="SELECT 'testdata' FROM 'testtable'") {
echo "Query";
}
if ($resultObject=mysqli_query($connectionObject, $queryString)) {
echo "Result";
}
if ($resultArray=mysqli_fetch_assoc($resultObject)) {
echo "Array";
}
while ($row=$resultArray) {
echo $row["testdata"];
print_r ($row);
}
mysqli_fetch_assoc returns an associate array of string representing the fetched row in the result set which is your $resultObject.
The problem is where you're using the while loop. You want to capture the returned associative array in a variable and access your data via that variable like follows:
while ($row = $resultArray) {
echo $row["rowName"];
}
To sort by rowName you can use the mysql order by clause in your query like follows which returns your results sorted by rowName:
$queryString = "SELECT rowName FROM tableName order by rowName";
Update after OP posted full code:
In your first if statement what would happen if the connection failed? You want to add some error handling there:
$connectionObject=mysqli_connect("host0", "username0", "password0", "mysqldatabase0"));
if (!$connectionObject) {
// exist out of this script showing the error
die("Error connecting to database " . mysqli_error($connectionObject));
} else {
// Don't really need this else but I'll keep it here since you already had it
echo "Con";
}
The problem is here You are using single quotes for column name and table name which are mysql identifiers. MySQL identifiers quote character is backtick not single quote.
Basically you need to use backticks if one of these identifiers are one of mysql reserved words (MySQL Reserved words), for other cases you don't need to use them.
Update your query:
if ($queryString="SELECT `testdata` FROM `testtable`") {
echo "Query"; // Leaving as is, not required
}
Lastly, an improvement. You want to add error handling here too:
if ($resultObject=mysqli_query($connectionObject, $queryString)) {
echo "Result"; // Leaving as is, not required
} else {
echo "Error executing Query " . mysqli_error($connectionObject);
}
Please note that when you use this script the error messages will be printed at the client i.e. when you use this script in a web application the errors will be shown in the user's browser. So you want to look into implementing logging and not printing them directly.
mysqli_fetch_assoc() returns one row as an associative array, of a mysqli_result object. Each time it is called, it returns the next row of results automatically and when used with a while loop, can be used to fetch an unknown number of result rows.
The $row['columnName'] is used to refer to the column. For example, if you had a person object with columns firstName, lastName, dateOfBirth, you could iterate through each person with a while loop as such:
while($row=mysqli_fetch_assoc($resultObject)){
$fname = $row['firstName'];
$lname = $row['lastName'];
$dob = $row['dateOfBirth'];
echo $fname . ' ' . $lname . ' ' . $dob;
}
This will echo details for a result returning an unknown amount of people.
Remember, calling the
if ($resultArray=mysqli_fetch_assoc($resultObject)) {
echo "Array";
}
before the while loop will skip the first result, so make sure the query returns multiple results when testing, as if you are only providing a resultObject containing one result, this might be why it isn't returning anything.
A better way to check if any results are returned is with the mysqli_num_rows($resultObject) function.
if(mysqli_num_rows($resultObject) > 0){
echo "Array";
}
Also not sure if it was just a typo but just to be sure, in your query you are selecting columnName not rowName:
$queryString = "SELECT columnName1(eg. firstName), columnName2(eg. lastName) FROM tableName";
I just recently started learning PHP, and the mysqli_fetch_assoc function confused me too, so I hope this helps!

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.

Categories