Skip to content
Advertisement

How to get data after @ in SQL

I have a table in the database that looks like this

id email
1 user@domain.com
2 user@domain2.com
3 user@domain3.com

I have a form that looks like this

<form action="action.php" method="post" class="email-form" name="email-form">
  <label for="email">Enter Email</label>
  <input type="email" class="email" id="email" name="email">
  <input type="submit" class="submit-email" name="submit-email" value="submit Email">
</form>

In the backend I’m trying to match the input email domain with the ones in the database, after “@”.

What I’ve tried (if user enters: test@domain2.com)

$email = $_POST["email"];
$emailDomain = explode("@",$email);
$emailDomain = $emailDomain[1];
/*I get the value domain2.com*/

How should I add a Query that matches $emailDomain with the database’s email domain.

I know that if I add

$sql = "SELECT * FROM table_name WHERE email = $emailDomain";

It will look for the exact email I want to look for whats after “@” in the email section

Advertisement

Answer

You already have the part after the @ stored in $emailDomain. Simply check whether the email field contains this value with the LIKE operator:

SELECT * FROM table_name WHERE email LIKE '%value%'

However, note that you cannot simply substitute value with your $emailDomain in the above query, as this would make it vulnerable to SQL injection. Instead, make sure to paramaterise the query, and use a prepared statement to avoid SQL injection:

$conn = new mysqli($servername, $username, $password, $dbname);

$email = $_POST["email"];
$emailDomain = explode("@", $email);
$emailDomain = $emailDomain[1];
$param = "%{$emailDomain}%";
$stmt = $conn->prepare("SELECT * FROM table_name WHERE email LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($result); // Store the output in $result
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement