Mysql validate and find the wrong emails - mysql

Suppose I have a table for user info records, each user may have email, but suppose instead of 'a#gmail.com', system inserted a#gmial.com or a#gmile.com and the same for yahoo, outlook, and hotmail.
But now I should find all the wrong emails, and replace the wrong domain name with correct one.
Something that i have tried before, but not bring the correct result:
select * from users where id not in
(select id form users where
strcmp(email,'#gmail') > 0 OR
strcmp(email,'#yahoo') > 0 OR
strcmp(email,'#hotmail') > 0 OR
strcmp(email,'#outlook') > 0
)

You can use the similar_text() http://php.net/manual/es/function.similar-text.php php function or the levenshtein(), i.e:
$users = //result from select * from users;
foreach($users as $user){
$u = end(explode('#',$user); //store the part of the email after '#'
echo "<br />Gmail:".similar_text($u,"gmail.com",$percent);
echo "<br />Yahoo:".similar_text($u,"yahoo.com",$percent);
echo "<br />Hotmail:".similar_text($u,"hotmail.com",$percent);
echo "<br />outlook:".similar_text($u,"outlook.com",$percent);
}
In this way, you will see the % of similarity between the emails, and then you can set the limit and replace the email for each email provider:
if(similar_text($u,"outlook.com",$percent) > 70){ //If the similarity is up to 70%
$user = substr(0,(str_pos($user,'#')-1))."#outlook.com"; //change the last part of the email for the desired one.
}
This is only a idea, i guess is not the better way to do it...

This would do what you want:
SELECT * FROM `users`
WHERE NOT(email LIKE '%#gmail%'
OR email LIKE '%#hotmail%'
OR email LIKE '%#yahoo%'
OR email LIKE '%#outlook%')
I would also suggest to extend your pattern a bit:
email LIKE '%_#gmail.__%'
This way you check also
There is at least one character before '#'
There is at least a two character domain extension

The obvious way to replace text is the REPLACE() function:
-- Untested
UPDATE users
SET email=REPLACE(email, '#gmile.', '#gmail.')
WHERE email like '%#gmile.%';
Repeat for each string (since it's a one time operation, trying to fit everything into a single query is just not worth the effort.)
In case you wonder, STRCMP(a, b)>0 is basically a convoluted replacement for a>b.

You can use strpos()
select * from users where id not in
(select id form users where
strpos(email,'#gmail') > 0 OR
strpos(email,'#yahoo') > 0 OR
strpos(email,'#hotmail') > 0 OR
strpos(email,'#outlook') > 0
)

Try this using INSTR:
select * from users
where
INSTR(email,'#gmail') +
INSTR(email,'#yahoo') +
INSTR(email,'#hotmail') +
INSTR(email,'#outlook')
= 0;

Did you realize that your nested query has FORM instead of FROM?
Anyway I would suggest you use LIKE instead of STRCMP.

Related

Using MD5 and CONCAT in MuSQL WHERE clause

I am creating a reset password procedure. this way:
1- Send reset email to the user (whom forgot his/her password), and this email contain a link to this address:
http://www.example.com/resetpassword.php?userid=1b2798bad6ee465d967cdb71ced504f7
The value of the parameter [userid] is generated by this PHP code:
<?php
md5($row_Recordset2['userID'].date('d-m-Y'));
?>
Note: I did this so that I can get a unique parameter value containing: The MD5 hash of the real user id + the current date (concatenation) , Why? so the link in the email will be available for the current date only. I do not want that link to work in the next day.
2- When the person click on the above link, he/she will be taken to the page [resetpassword.php]
3- In the page [resetpassword.php] page I have this piece of code:
$colname_Recordset1 = "-1";
if (isset($_GET['userid'])) {
$colname_Recordset1 = $_GET['userid'];
}
mysql_select_db($database_aaa_database, $aaa_database);
$query_Recordset1 = sprintf("SELECT * FROM users WHERE md5(CONCAT(userID,
DATE_FORMAT(NOW(),'%d-%m-%Y'))) = %s ", GetSQLValueString($colname_Recordset1,
"text"));
$Recordset1 = mysql_query($query_Recordset1, $aaa_database) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
The SELECT statement return [Query was empty] ... What is the problem and how to solve it?
I have tested this MySQL statement manually:
SELECT userFirstName, md5(CONCAT(userID, DATE_FORMAT(NOW(),'%d-%m-%Y'))) from users
And it return many rows, one of the rows is like this:
Sam 1b2798bad6ee465d967cdb71ced504f7
So, the:
md5(CONCAT(userID, DATE_FORMAT(NOW(),'%d-%m-%Y')))
works fine and it return the same exact value generated by the PHP code :
<?php
md5($row_Recordset2['userID'].date('d-m-Y'));
?>
PHP give: 1b2798bad6ee465d967cdb71ced504f7
MySQL give: 1b2798bad6ee465d967cdb71ced504f7
But this:
md5(CONCAT(userID, DATE_FORMAT(NOW(),'%d-%m-%Y')))
seems to be NOT WORKING in the WHERE clause:
sprintf("SELECT * FROM users WHERE md5(CONCAT(userID,
DATE_FORMAT(NOW(),'%d-%m-%Y'))) = %s ", GetSQLValueString($colname_Recordset1,
"text"));
By the way, I am using Dreamweaver.
I don't know how to solve this problem. Any help will be highly appreciated.

How to make like and unlike

I have tried to make like and like system using ajax and mysql.
Click like, like is added and Click again, like min 1.
I want, when I click unlike, it will back to like.
But this, unlike until minus..
This is my mysql
<?php
include 'connect.php';
session_start();
$ip=$_SESSION['id'];
if ($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysql_query("select id_user from social where track_id='$id' and id_user='$ip'");
$count=mysql_num_rows($ip_sql);
if ($count==0)
{
$sql = "update track set jumlah_like=jumlah_like+1 where track_id='$id'";
mysql_query($sql);
$sql_in = "insert into social (id_user,track_id) values ('$ip','$id')";
mysql_query($sql_in);
$result=mysql_query("select jumlah_like from track where track_id='$id'");
$row=mysql_fetch_array($result);
$love=$row['jumlah_like'];
?>
<span class="broke_love" align="left"><?php echo $love; ?></span>
<?php
}
else
{
$sql = "update track set jumlah_like=jumlah_like-1 where track_id='$id'";
mysql_query($sql);
//$sql_in = "insert into social (id_user,track_id) values ('$ip','$id')";
//mysql_query($sql_in);
$result=mysql_query("select jumlah_like from track where track_id='$id'");
$row=mysql_fetch_array($result);
$love=$row['jumlah_like'];
echo "<span class=on_img align=left>$love</span>";
}
}
?>
The problem is algorithmic that is causing your button to be stuck on 'unlike'.
Your basic condition is: if ($count==0) which always returns greater than 0 after the statement $sql_in = "insert into social (id_user,track_id) values ('$ip','$id')"; is run.
Therefore, your code gets stuck in always executing the else, and continously diminishing the likes.
You need to change your logic to be more:
Check if likes exist and add for specific user.
If like already exists, remove like record.
I think you are missing something from your script as you do not appear to remove a record from the table social.
However most of your selects and updates can be done with a single piece of SQL. Something
like:-
UPDATE track a
LEFT OUTER JOIN social b ON a.track_id = b.track_id AND id_user='$ip'
SET a.jumlah_like = a.jumlah_like + IF(b.track_id IS NULL, 1, -1)
It would probably be better to have a votes table rather than adding and deleting records on the social table. One row per vote.

User Search Query to SQL Where Clause

Are there pre-existing libraries that will take a user input and transform it into a SQL WHERE clause?
For example given a database that has columns first_name, last_name, and address the user could input something like:
John State St
and the library would build a query such that it would return rows that match a guy named John that lived on State St (or a guy named State that lived on John St, for that matter).
It could also support things like specifying the column:
first_name:John address:State
I have some simple code to handle some of these cases already but it's getting a little unwieldily. I would think there are some pre-existing solutions to this problem but I'm having a hard time finding them. Generally, the problem is how to enable the user to easily search a structured database with a single input field.
In this matter you can break down string as multiple values using string manipulation, and then search for each word in each column using "or" conditions.
additionally you can define index on columns so as to achieve faster search.
You might have tried this technique since you mentioned, but you have to look up each word in each column
Jquery UI autocomplete could be what you are looking for. the css along with it is also necessary please see this link http://api.jqueryui.com/autocomplete/ for the .js ans css needed.
$( "#myInputBoxId" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
and in search.php
<?php
include 'config.php';
$results =array();
$req = "SELECT product_name "
."FROM table4 "
."WHERE product_name LIKE '%".$_REQUEST['term']."%' LIMIT 5";
$query = mysqli_query($con,$req);
while($row = mysqli_fetch_array($query))
{
array_push($results,$row['product_name']);
}
echo json_encode($results);
}

MySql: Best way to run high number of search queries on a table

I have two tables, one is static database that i need to search in, the other is dynamic that i will be using to search the first database. Right now i have two separate queries. First on page load, values from second table are passed to first one as search term, and i am "capturing" the search result using cURL. This is very inefficient and probably really wrong way to do it, so i need help in fixing this issue. Currently page (html, front-end) takes 40 seconds to load.
Possible solutions: Turn it into function, but still makes so many calls out. Load table into memory and then run queries and unload cache once done. Use regexp to help speed up query? Possible join? But i am a noob so i can only imagine...
Search script:
require 'mysqlconnect.php';
$id = NULL;
if(isset($_GET['n'])) { $id = mysql_real_escape_string($_GET['n']); }
if(isset($_POST['n'])) { $id = mysql_real_escape_string($_POST['n']); }
if(!empty($id)){
$getdata = "SELECT id, first_name, last_name, published_name,
department, telephone FROM $table WHERE id = '$id' LIMIT 1";
$result = mysql_query($getdata) or die(mysql_error());
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo <<<PRINTALL
{$row[id]}~~::~~{$row[first_name]}~~::~~{$row[last_name]}~~::~~{$row[p_name]}~~::~~{$row[dept]}~~::~~{$row[ph]}
PRINTALL;
}
}
HTML Page Script:
require 'mysqlconnect.php';
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$getdata = "SELECT * FROM $table WHERE $table.mid != '1'ORDER BY $table.$sortbyme $o LIMIT $offset, $rowsPerPage";
$result = mysql_query($getdata) or die(mysql_error());
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$idurl = 'http://mydomain.com/dir/file.php?n='.$row['id'].'';
$p_arr = explode('~~::~~',get_data($idurl));
$p_str = implode(' ',$p_arr);
//Use p_srt and p_arr if exists, otherwise just output rest of the
//html code with second table values
}
As you can see, second table may or may not have valid id, hence no results but second table is quiet large, and all in all, i am reading and outputting 15k+ table cells. And as you can probably see from the code, i have tried paging but that solution doesn't fit my needs. I have to have all of the data on client side in single html page. So please advice.
Thanks!
EDIT
First table:
id_row id first_name last_name dept telephone
1 aaa12345 joe smith ANS 800 555 5555
2 bbb67890 sarah brown ITL 800 848 8848
Second_table:
id_row type model har status id date
1 ATX Hybrion 88-85-5d-id-ss y aaa12345 2011/08/12
2 BTX Savin none n aaa12345 2010/04/05
3 Full Hp 44-55-sd-qw-54 y ashley a 2011/07/25
4 ATX Delin none _ smith bon 2011/04/05
So the second table is the one that gets read and displayed, first is read and info displayed if ID is positive match. ID is only unique in the first one, second one has multi format input so it could or could not be ID as well as could be duplicate ID. Hope this gives better understanding of what i need. Thanks again!
A few things:
Curl is completely unnecessary here.
Order by will slow down your queries considerably.
I'd throw in an if is_numeric check on the ID.
Why are you using while and mysql_num_rows when you're limiting to 1 in the query?
Where are $table and these other things being set?
There is code missing.
If you give us the data structure for the two tables in question we can help you with the queries, but the way you have this set up now, I'm surprised its even working at all.
What you're doing is, for each row in $table where mid!=1 you're executing a curl call to a 2nd page which takes the ID and queries again. This is really really bad, and much more convoluted than it needs to be. Lets see your table structures.
Basically you can do:
select first_name, last_name, published_name, department, telephone FROM $table1, $table2 WHERE $table1.id = $table2.id and $table2.mid != 1;
Get rid of the curl, get rid of the exploding/imploding.

PHP Array Duplicates

my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
What I would like to do is display each user individually, and count the number of contacts each user has. I had a look at the post "How to detect duplicate posts in PHP array, which helped a bit, but I am still stuck.
Please see my code for the query below, I have left out the array duplicate part as it is a pretty mess at the moment.
<?php
$result = mysql_query("SELECT * FROM vines");
while($row = mysql_fetch_array($result)) {
$results=$row['vinename'];
echo $results;
echo "<br />";
}
?>
This result returns the below, obviously these are records from the vinename coloumn.
Marks Vine<br />
Marks Vine<br />
Marks Vine<br />
Tasch Vine<br />
Tasch Vine<br />
Regards
Mark Loxton
Hi there, my first post here and hoping someone can help. I am querying a table in a mySQL DB, and obviously getting the results. However, the table is used to store multiple entry by one user for the purpose of user contacts.
You can do this in the query itself a lot more easily than in the PHP code afterwards.
SELECT name, COUNT(id) AS count FROM vines GROUP BY name
Just change the SQL Query to
SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename
and then do
echo $row['vinename']." #".$row['counter']."<br />";
I would run two types queries...
1) Select each UNIQUE user from vines.
2) For each user in that set, run a second COUNT query against that user's id in the table "vines".
I hope that helps.
You can create a separate array to store records you've already output there.
<?php
$result = mysql_query("SELECT * FROM vines");
$duplicates = array(); ## store duplcated names here
while($row = mysql_fetch_array($result)) {
$results = $row['vinename'];
if (!array_key_exists($results, $duplicates)) {
echo $results;
echo "<br />";
$duplicates[$results] = 1; ## mark that we've already output this records
}
}
?>
You can try, change your query to use count and group of SQL.
Somoe thing like
$result = mysql_query("SELECT count(*) as total,name FROM vines GROUP by name");
firstly thank you everyone for such awesome input. I seriously did not expect such a quick response. I am seriously grateful.
I used the recommendation from Jitter. I have pretty much been going through so many variations of the above code today, but just needed that missing piece.
Thanks, everyone. Below is what the final code looks like for anyone else who has the same problem in the future.
<?php
$result = mysql_query("SELECT vinename, COUNT(vinename) as counter FROM vines GROUP BY vinename ORDER BY counter DESC LIMIT 0, 3");
while($vinerow = mysql_fetch_array($result))
echo $vinerow['vinename']." has ".$vinerow['counter']." tomatos."."<br />";
?>
change your query to:
SELECT distinct * FROM vines