searching for a string while looping - php

I am trying to format another sites data to insert into my database. He wants to close his site, so is giving me his sites listings. But im having to format his data from his flatfile database, to go into my mysql database.
Im looping through his text file, and getting his values. Then formatting as needed before inserting them into my DB.
Because our sites use completely different storage formats and fields, im having a few problems with something.
My site has a designer field. His doesnt. so im trying to search through his description field to find a match within my designer table. If there is a match i want to get the designer ID to insert into the designer id field. But i cant get this code to work.
Could someone please suggest a fix? or if theres a better way to do this?
$fp = fopen('listings.txt','r');
if (!$fp) {echo 'ERROR: Unable to open file.'; exit;}
$loop = 0;
while (!feof($fp)) {
$loop++;
$line = fgets($fp,1024); //use 2048 if very long lines
$field[$loop] = explode (' ', $line);
$get_designers = mysql_query("SELECT * FROM dress_designers");
$row_designers = mysql_fetch_array($get_designers);
$totalRows_designers = mysql_num_rows($get_designers);
do{
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
$mystring = strtolower($field[$loop][8]);
$findme = strtolower($row_designers['designer_name']);
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
$designer = "Other";
} else {
$designer = "Siopa Rince";
}
} while ($row_designers = mysql_fetch_assoc($get_designers));
$fp++;
}
fclose($fp);
I only put "Siopa Rince" as a test. But this isnt working. If i take the text from the file, and paste it in the $mystring and put siopa rince in $findme... it works.
Any suggestions would be greatly appreciated!
Thanks,
Danny
OK... what about just entering the info as is? I tried a few different ways, but the result is returning null...
After i insert the data, ill use searches to join the required row to get an ID:
SELECT dress_test.dress_title, (
SELECT dress_designers.designer_id
FROM dress_designers
WHERE MATCH (
dress_test.dress_desc
)
AGAINST (
'dress_designers.designer_name'
IN boolean MODE
)
) AS real_designer_id
FROM dress_test
Another version:
SELECT dress_test.dress_title, dress_designers.designer_name
FROM dress_test
JOIN dress_designers ON MATCH(dress_test.dress_title, dress_test.dress_desc) AGAINST
('dress_designers.designer_name' in boolean mode)
Any other suggestions??

Your first assignment to $row_designers uses mysql_fetch_array, while your second uses mysql_fetch_assoc
Instead of do { ... } while, why not just while () { ... }
Remove this line $row_designers = mysql_fetch_array($get_designers);
And turn your loop into...
while ($row_designers = mysql_fetch_assoc($get_designers)) {
// string search here
}
Everything else looks fine - if you're having troubles, check the values with either echo to print string or print_r to print arrays.

Related

Return true/false if word in URL matches specific word

I currently use:
if(strpos($command->href,§current_view) !== false){
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}
$command->href will output something like this: /path/index.php?option=com_component&view=orders Whereas
§current_view is outputting orders. These outputs are dynamically generated, but the scheme will always be the same.
What I need to do is return true/false if the words from $current_view match the view=orders in the URLs from $command->href. The issue with my code is, that it doesnt match anything.
What is the correct way to do this?
Please note that the $command->href and the whole code is inside a while function, that pass multiple URLs and this only needs to match the same ones.
Breaking it down to a simple example, using your code and variable values.
$current_view = 'orders';
$command = '/path/index.php?option=com_component&view=orders';
if(strpos($command,$current_view) !== false){
echo '<pre>true</pre>';
}
else {
echo '<pre>false</pre>';
}
The oputput is "true".
Now, go and debug the REAL values of $command->href and $current_view...
I'm pretty confident that the values are not what you think they are.
Does something like:
if(substr($command->href, strrpos($command->href, '&') + 6) == $current_view)
accomplish what you are after?
To explain, strpos get the last instance of a character in a string (& for you, since you said it always follows the scheme). Then we move over 6 characters to take "&view=" out of the string.
You should now be left with "orders" == "orders".
Or do you sometimes include some arguments after the view?
Try parsing url, extracting your view query string value and compare it to $current_view
$query= [];
parse_str(parse_url($command->href)['query'], $query);
if($current_view === $query["view"])
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}

PHP explode string on if

My code that reads an XML file is as follows:
<?php
if ( $dance['block'] == $dance['user']['ip'] ) : ?>
<?php e(o("N/A")) ?>
Right now, that if() statement is reading the entire XML file as one string. So next I used:
$array6 = explode(",", $this->block);
$result['block'] = (string) $array6;
This was supposed to explode each $dance['user']['ip'], but I'm not sure why it's not working.
Any ideas, fixes, or tips?
Casting an array to a string will unhelpfully give you the string "Array" as well as throw a nifty warning. I'm not quite sure what you are trying to accomplish there.
For your test to see if a user's ip is in the block list you should do the following:
$blockList = explode(",", $blockedIpString);
if (in_array($dance['user']['ip'], $blockList)){
// user is blocked
} else {
// user is not blocked
}

preg_match and reg expression using alphanumeric, commas, periods, exclamations, etc

I am having one hell of a time coming up with a decent way make this if statement search a file for these codes. I set up the text file to read from as such:
myfile.txt
r)
0Y7
1a6
q.
#g
#(
#a
!P
T[
V}
0,
Here is a brief of what I got going.
$subject = file_get_contents(fvManager_Path . 'myfile.txt');
if ( preg_match('/^[a-zA-Z0-9,]+$/',$result['fmbushels_itemCode'], $subject) ) {
Basically I am trying to search the text file line by line to see if the whole string exists. They are case sensitive as well.
$result['fmbushels_itemCode'] is from a sql query and always returns a code like the above in the text.
I'd appreciate any help on this. If someone knows a better way of doing this or a different command, I'd be willing to give that a shot as well :)
edit:
private function _fvShareBushels() {
$subject = file_get_contents(fvManager_Path . 'myfile.txt');
if (count($vShareArray) > 0) {
$vCntMoves = count($vShareArray);
for ($vI = 0;$vI < $vRunMainLoop;$vI++) {
sell $result['fmbushels_itemCode']);
}
}
}
This is a snippet of a big code. I had to rip most out because of post limitation. The area I could be working with is:
if (count($vShareArray) > 0) {
If I could make this something like:
if (count($vShareArray) > 0 && $result['fmbushels_itemCode'] **is not in** $subject) {
If you want to do line by line, use the file() function.
$f = file(fvManager_Path . 'myfile.txt');
foreach($f AS $line){
// $line is current line at file
}
I'm not to sure if you understand completely how preg_match works. The first parameter is the regular expression pattern, the second is what you want to match the pattern to, and the third is an array of matches. So for every valid pattern matched in the second parameter a new index on the array is created.
I'm not 100% on what you're trying to accomplish. Are you trying to see if the $result['fmbushels_itemCode'] exists in the file?
If the above is the correct case you simply just need to do something like:
$f = file('myfile.txt');
array_map('trim', $f);
if(in_array($result['fmbushels_itemCode'], $f)){
// success
}

Passing Object Operators As Strings (PHP)

I'm building a script that takes the contents of several (~13) news feeds and parses the XML data and inserts the records into a database. Since I don't have any control over the structure of the feeds, I need to tailor an object operator for each one to drill down into the structure in order to get the information I need.
The script works just fine if the target node is one step below the root, but if my string contains a second step, it fails ( 'foo' works, but 'foo->bar' fails). I've tried escaping characters and eval(), but I feel like I'm missing something glaringly obvious. Any help would be greatly appreciated.
// Roadmaps for xml navigation
$roadmap[1] = "deal"; // works
$roadmap[2] = "channel->item"; // fails
$roadmap[3] = "deals->deal";
$roadmap[4] = "resource";
$roadmap[5] = "object";
$roadmap[6] = "product";
$roadmap[8] = "channel->deal";
$roadmap[13] = "channel->item";
$roadmap[20] = "product";
$xmlSource = $xmlURL[$fID];
$xml=simplexml_load_file($xmlSource) or die(mysql_error());
if (!(empty($xml))) {
foreach($xml->$roadmap[$fID] as $div) {
include('./_'.$incName.'/feedVars.php');
include('./_includes/masterCategory.php.inc');
$test = sqlVendors($vendorName);
} // end foreach
echo $vUpdated." records updated.<br>";
echo $vInserted." records Inserted.<br><br>";
} else {
echo $xmlSource." returned an empty set!";
} // END IF empty $xml result
While Fosco's solution will work, it is indeed very dirty.
How about using xpath instead of object properties?
$xml->xpath('deals/deal');
PHP isn't going to magically turn your string which includes -> into a second level search.
Quick and dirty hack...
eval("\$node = \"\$xml->" . $roadmap[$fID] . "\";");
foreach($node as $div) {

Getting part of MySql row?

Is there any way to get just a part from MySql cell and ignore everything after predefined character?
For example, I have row with cell's "ID, LINK, PHONE". Inside LINK cell DB wrights links like mysite.com/mypicture.jpeg. Is there any way, to get just "mysite.com" from this cell and ignore everything after slash, so I can echo it inside anchor tag?
Edit: To be absolutely clearly I'm posting the existing code:
<?PHP
if(mysql_connect($db_host,$db_user,$db_pass)) {
mysql_select_db($db_name);
mysql_query("CREATE TABLE IF NOT EXISTS smsads(id bigint unsigned primary key auto_increment, link varchar(255), fromnum varchar(60))");
$res = mysql_query("SELECT * FROM smsads ORDER BY id DESC LIMIT 3");
while($row = mysql_fetch_object($res)) {
$http_link = $row->link;
if(strstr($http_link, 'http') === FALSE) $http_link = 'http://'.$http_link;
echo "<div id=\"banner\"><img src=\"{$http_link}\" /></div>";
}
}
?>
SELECT SUBSTRING_INDEX(link,'/',1);
should do the trick. It will return everything before the first slash character
A solution, on the PHP side, might be to use strpos and substr, to :
find the position of the character
and extract what comes before/after.
A bit like this, for instance :
$str = 'mysite.com/mypicture.jpeg';
$position = strpos($str, '/');
if ($position !== false) {
$before = substr($str, 0, $position);
$after = substr($str, $position+1);
var_dump($before, $after);
}
Which will get you :
string 'mysite.com' (length=10)
string 'mypicture.jpeg' (length=14)
If you know there will always be one (and only one) slash in your data, you can also use explode and list :
list($before, $after) = explode('/', $str);
var_dump($before, $after);
Which will give you the same output :
string 'mysite.com' (length=10)
string 'mypicture.jpeg' (length=14)
Another idea would be to do that on the SQL side -- if you need both fields, though, doing it on the PHP side is not a bad idea (both sides, PHP and SQL, are valid, actually).
EDIT after the comments.
What about something like this, for your loop :
while($row = mysql_fetch_object($res)) {
$http_link = $row->link;
$position = strpos($http_link, '/');
if ($position !== false) {
$before = substr($http_link, 0, $position);
if(strstr($http_link, 'http') === FALSE) {
$http_link = 'http://'.$http_link;
$before = 'http://' . $before;
}
echo "<div id=\"banner\"><img src=\"{$http_link}\" /></div>";
}
}
For each line, you are getting the $row->link to the $http_link variable, like you did before.
Then :
you extract the part that comes before the '/' ; and use it for the a href tag, to link to the root of the website
you use the full URL from the DB, for the img src tag, to display the image
And you don't forget to add 'http://' if necessary to both URLs, like you did at the first place when you only had one.
Note : that code is not tested, but should give you a hint of a possible solution.
Hope this helps :-)
Something like this:
SELECT substring_index(substring_index('http://google.com/path?blah=1&2.1','/',3),'/',-1)
will work or full urls.
edit: added example for partial url:
select substring_index('google.com/path?blah=1&2.1','/',1);
In your case, replace
$res = mysql_query("SELECT * FROM smsads ORDER BY id DESC LIMIT 3");
with
$res = mysql_query("SELECT link,substring_index(link,'/',1) host FROM smsads ORDER BY id DESC LIMIT 3");
This should work assuming your urls are always without the http:// part. (if they are with it, use the other example I provided).
Using substring on the LINK column on the database side or on the data once you have on the client side is an option, but depending on what you're doing here and how many rows you can expect in this table, I would consider breaking that field out into a separate column in your table so you only have to calculate it once at insert time. Then you can index it, easily block certain ones from being inserted, etc.
Going from there, depending on your needs, you may want to further normalize the LINK in order to store host and domain portions only once and having a key back to the path and filename. You can do all this, and then for convenience you can make a view to pull them all together for your application and users to use.

Categories