Match urls mysql - php

$value = 'http://www.mydomain.com/this-is-page-one'
I have a field in my mysql table called "urls" which stores different urls inside, like:
http://www.bdsada.com/dsadsfsaf
http://www.comddsad.com/dsadacsdfs
and so on
I want to best match my value with on of the urls. - do an sql query
Maybe the number of repeatting letters.
Please give an actual example.... pleaseee

Not sure exactly what you mean by the 'best match'. Say that you are storing the urls in the database as listed above (http://www.website.com/extension). Also, that the input may or may not include the 'http://', 'www.', or any additional GET variables in the URL. Before you submit the string for the database query, I would do the following:
To strip the 'http://' or 'https://' from the url.
$valueStrip = explode("//",$value);
$value = $valueStrip[1];
To strip out any get variables
$valueStrip = explode("?",$value);
$value = $valueStrip[0];
Also, make sure you clean it for any SQL injection attack, this should work
$value = mysql_real_escape_string($value);
Let assume that 'url' is the name of the table and 'domainName' is the column name for the actual domain name. So, your query could look like this
$query = mysql_fetch_array(mysql_query("SELECT url FROM domainName WHERE url LIKE '%$value%'"));
I should note that I haven't tested the code and it could be made more efficient.

Related

SQL/PHP - REPLACE statement not working as intended

I'm trying to 'remove' part of a string in a DB entry after a delete command is made.
Say a PDF file gets deleted, i want to remove the reference of it by replacing it with '' (but keep the other references). That works fine, but now i also want to do it with another column, and the exact same setup doesn't seem to work and i can't figure out why.
This works:
$stmt_2 = $db->prepare("UPDATE data_videothek SET pdfAttachment = REPLACE(pdfAttachment, $id, '') WHERE pdfAttachment LIKE ?");
$stmt_2->execute(array( $like_id_string ));
This doesn't:
$stmt_2 = $db->prepare("UPDATE data_videothek SET speaker_img = REPLACE(speaker_img, $thefile, '' ) WHERE speaker_img LIKE ?");
$stmt_2->execute(array( $like_filename_string ));
Both columns are defined as 'varchar' and all input in the query is as 'string'
I can't wrap my head around why the pdf one works, but the speaker_img doesn't.
The problem must be in REPLACE(speaker_img, $thefile, '' ) because if i replace that with a simple = '', the query performs fine and clears the whole cell if a match is made.
This is how i define the 2 input variables:
$thefile = (string)basename($row['filename'], ".png");
$like_filename_string = "%".$thefile."%";
For the curious why i save the info like that: There's only 1 field for the filenames, seperated by a "-", which when loaded gets 'exploded' into an array. It allows me to haven an open-ended number of attachments. Maybe not the best way of doing things?
If you use parameters for $id and $thefile instead of variable interpolation, you won't need to worry about escaping chars, which is probably the reason the sql is malformed when you try to just use the value of $thefile inside a sql string.

How to find a needle in database sql

I have query which search for database, that is
$linkcdb = $wpdb->query($wpdb->prepare("SELECT wp_link_factor WHERE wp_link_chk = %s", $u));
where $u = is nay link;
for example;
$u = www.kaka.com
$u = popopo.com
$u = http://jajaja.com
I have a data base in which www, http and .com is in the column of table and the column name is wp_link_chk
Now the problem I am facing is the user input is a complete link like www.example.com while in database I had only .com, http and www
What I want is that how I compare my complete sentence and see if the sentence have needle http, or www or .com in it ?
The function that do this is stristr($u,'http') so how I am going to use this functionality in data base, I mean how i am going to check the column of wp_link_chk as a needle against my sentence ?
Using the MySQL function LOCATE you could use something like
... WHERE LOCATE( wp_link_chk, :userInput ) > 0
Edit: Note that this approach may of course return multiple records, for instance if "http://www.example.com" is matched against "http", "www", and ".com".
Well, the closest way to match these is to use the mysql LIKE function.
The actual statement would be something like
SELECT wp_link_factor WHERE wp_link_chk LIKE %www.example.com%
But since you are using wordpress prepared statements, use it like this:
$linkcdb = $wpdb->query($wpdb->prepare("SELECT wp_link_factor WHERE wp_link_chk LIKE %s", '%' . $u . '%'));
-- UPDATE --
For the sake of completion, you can use REGEXP matching to select rows that contains either http, www or .com in the wp_link_chk column using the following query.
SELECT wp_link_factor WHERE wp_link_chk REGEXP '(http)|(www)|(\.com)'

Get product name in url rather than id php

I am working on a shopping cart website for a university project and need some help.
The site is currently under production at http://www.cutecupcak.es.
At the moment, each product has a url of something like http://cutecupcak.es/product.php?id=11, but I want it to be something like http://cutecupcak.es/product.php?id=chocolate_cupcake.
This is the code we have been given to make this work.
if(isset($_GET['id'])) {
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_id`=($id)");
}
What do I need to change to get the cake_name to show rather than the cake_id?
Generally, if you want to reference your products by a name instead of id - you should add a new column (I always name it as "slug") with an UNIQUE key. Then, when product is added or edited, based on its name you generates new value for the slug column. For example - from "Chocolate Cake" you will create "chocolate_cake". Then you have to check if the slug is unique - and if not - resolve conflict somehow (e.g. "chocolate_cake_1").
If you have all this set up - just select the appropriate product by unique slug:
$result = mysql_query("SELECT * FROM `CAKE` WHERE `slug`='" . mysql_real_escape_string($_GET['id']) . "'");
And - obviosuly - use mysqli instead of deprecated mysql functions.
http://php.net/manual/en/mysqli.query.php
You can put the name in the url, which should be quite simple, since you have both the name and the id in your database and you can search by and use both.
Both name and id
But I would advise against it. Product names can change a little, and changing it means that the old link wont work anymore.
I would create an url like this:
http://cutecupcak.es/product.php?id=11&name=chocolate_cupcake
or rather even:
http://cutecupcak.es/product/11/chocolate_cupcake
These urls can be indexed safely. You retain the numeric id, which you can use to lookup the number. The name is in the url as well, which is good for readability and for SEO (search engine optimization), but the name has no actual meaning. You can safely ignore it, because you got the number. Therefor all previously indexed and linked urls will remain valid after you change the name.
I would choose to use dashes instead of underscores in the product name. I believe chocolate-cupcake and chocolate+cupcake are both indexed better than chocolate_cupcake, but my information on this topic may be a bit stale.
mysql? Parameters!
I also would advise you to no longer use mysql_*, and start using PDO or mysqli. Both allow the use of parameterized queries. This allows you to pass an id or name to a query in a safe and transparent method. Safer, cleaner and better performing than using mysql_real_escape_string or functions like that. It's especially safer, because once you become accustomed to using parameters, you will start passing all variables as parameters. While you can forget to escape a variable in your current query, you cannot possibly forget to escape a variable, because it doesn't need escaping.
Try something like this:
if(isset($_GET['id'])) {
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_name`=(". mysql_real_escape_string($id). ")");
}
Note: I also added mysql_real_escape_string, as not doing that poses a huge SQL injection risk.
I think this just changes to:
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_name`=($id)");
The Following is a blueprint to what you have to do:
1- In your table you should set cake_name field to be unique.
2- Your sql query should be:
$result = mysql_query("SELECT * FROM `CAKE` WHERE `cake_name`=($id)");
3- Change the links found of your products list to obtain the cake_name value instead of the numeric id.

Dynamic lead capture script

I'm creating a dynamic lead capture script.
The form passes the table name, and the rest of the post data.
I'm looking for a way to collect all the post inputs and insert that into a MySQL table without knowing the input names since each 'lead' script is different and contains different fields.
The table is already created and contains all the columns necessary for the input.
Any clean ideas?
Cheers!
A quick solution is to serialize an array of your validated post data. This will convert it into a string for storing in your Database.
You can unserialize that string to convert it back into a manageble array.
http://php.net/manual/en/function.serialize.php
The biggest downside is not having the full SQL support that you would have otherwise, by putting data into separate database fields.
I would use a combination of both techniques by putting consistant data like names, email into their own fields and unknown data into another field.
--
Try index identification (if you don't know the specific names):
$data = array_values($_POST);
$name = $data[0];
$email = $data[1];
$etc = $data[2];
--
Generate SQL string from data. Remember be vigilant with validation and ideally you should use Mysqli bind params to correcly build your query string.
foreach($_POST as $input_name => $input_value){
//do validation here
//match columns here
if($input_name=='name') $cleaned[$input_name] = $input_value;
}
$values_csv = '"'.implode('","',$cleaned).'"';
$sql = "INSERT INTO table_name VALUES ($values_csv);";

php, how to get the keywords out of an url?

the question might be a bit confusing, so here is what i have:
i insert in the database the previous link where a person came from like tihs:
$came_from = $_SERVER['HTTP_REFERER']; // get previous link
if the link is from google.com it will come like this:
http://www.google.com/#sclient=psy&hl=en&source=hp&q=this+is+a+test&pbx=1&oq=this+is+a+teat&aq=f&aqi=g-s1g-v1&aql=1&gs_sm=s&gs_upl=887l82702l3.10.3.1l17l0&bav=on.2,or.r_gc.r_pw.r_cp.&fp=c3d3303&biw=1920&bih=995
if we look inside we can find q=this+is+a+testas beeing the keywords that i search for.
my question is how can i create a query to return http://www.google.com/ | this+is+a+test ?
i know that the keywords have the + sign in between them.
so far i came up with this, but not exactly what i wanted:
SELECT SUBSTRING_INDEX (table, '+', 1), table FROM table.table WHERE table LIKE '%+%' LIMIT 20
any ideas?
thanks
edit: what happend is that sometimes i get some other url's that don't have q= but maybe seearch=, so i want to keep track of the + sign
As it's been pointed out, you can't reliably get the keywords without supplying the parameters to look for. Here's what I would do:
$url = 'http://www.google.com/#sclient=psy&hl=en&source=hp&q=this+is+a+test&pbx=1&oq=this+is+a+teat&aq=f&aqi=g-s1g-v1&aql=1&gs_sm=s&gs_upl=887l82702l3.10.3.1l17l0&bav=on.2,or.r_gc.r_pw.r_cp.&fp=c3d3303&biw=1920&bih=995';
$possible = array('q', 'ssearch', 'oq');
$query_str = NULL;
foreach ($possible as $search) {
if (isset($arr[$search])) {
$query_str = $arr[$search];
break;
}
}
Basically all this does is parse the url using PHP's parse_str() and look for the parameter q. If it's not there, it uses ssearch, and then oq. You can add more of them if you need to. If by the end of it it's not found, $query_str will be NULL.
Unless you have a very compelling reason to do it with MySQL only, just process everything on the PHP side. Databases are made to store data, not process it. What I would do is have PHP figure out the search engine and the keywords used and insert those into the DB, as separate fields. ie, have a table like so:
search_engine | query_str
------------- | -----------
google | test
yahoo | something
...
If you know that you need q=... then you can use regexp. I will update post if that's what you need.
As everyone is saying, you need to use the key value (in your example, q). In MySQL, you can do something like this:
SELECT SUBSTRING_INDEX(table, '?q=', -1), table FROM table.table WHERE table LIKE '?' LIMIT 20
I'd also suggest you rename your table column to something other than 'table'.

Categories