PHP email suffix using CONCAT() - php

Trying to use a php generating the email address using the ID eg: peopleID from database using query function with people_mysql into an HTML table with array of emails from five people. The database do not have email addresses only peopleID in a field. Email suffix is #dot.com.
To explain better to what I'm talking about.
$peopleid = "12345";
$suffix = "#dot.com";
$email = $peopleid . $suffix;
// where $email then contains "people#dot.com" with MySQL
This is what I've come up with with string operator.
mysql> SELECT * FROM 'people';
mysql> SELECT *, CONCAT('peopleID', '#dot.com') AS 'Email' FROM 'people';
I would be grateful if anyone can come a php code.

Your query has a mistake in it. Look at the character just before the # symbol. It should be a single quote.
$emails = array();
$query = "SELECT *, CONCAT('peopleID', '#dot.com') AS 'Email' FROM 'people'";
$result = mysql_query($query,$conn_to_database);
while($row = mysql_fetch_object($result)):
$emails[] = $row->Email;
endwhile;
MySQL queries return a reference to the results, not the results themselves. So, you then need to fetch each row and perform any actions you need to perform. In this case, you are populating and array named $emails that you can then use in your php code.

Related

PHP determine if email appears more than once in SQL query results

We are working on a small follow up email script and now need to determine if an email appears more than once in the query results. If the email appears only once then use email content A, if it appears more than once use email content B.
We are using a fairly standard PHP query and then using a while loop to tackle each row:
// query database followups for rows which fupdate = todays date
require 'user password stuff.php';
$today = date("Y-m-d");
// tourname, email, tourid, fupsent
$fups = $database->query("SELECT * FROM followups WHERE fupdate='$today'");
while ($followup = $fups->fetch(PDO::FETCH_ASSOC))
{
$email = $followup["email"];
// check if email appears more than once
// the code we need...
if ($emailcount === 1) {
// include content A in email body
} else {
// include content B in email body
}
}
Is there an auto-magical way to perform such a task? Or are we limited to setting up another query / while loop to compare the email to every other and counting how many times it matches one?
Some additional clarification:
We are working with only one table, which contains: fupdate, email, name, productid (plus a few other columns which aren't related to this function).
Any duplicated emails would have unique productid
--- Got It Sorted ---
It was a tough choice as to the accepted answer, both had the same focus and were written within minutes of each other, but Qirel went a bit further with their explanation.
The final version is quite different than the original concept, as now we will first use the COUNT(*) and GROUP by email functions to fetch a list of unique emails to process, then do a 2nd query using JOIN to combine the followups and product tables to gather customer name plus product names and urls to build the email content.
My thanks to all three who provided answers/comments, as all contributed to the final ideas.
You should be using a prepared statement with your query, to avoid injecting variables directly into your SQL query.
To get the number of occurrences of an entry, use GROUP BY email, and then use the aggregate function COUNT(), which will give you the count of each email matching the condition in your WHERE clause.
The query then becomes
SELECT email, COUNT(*) as email_count
FROM followups
WHERE fupdate = ?
GROUP BY email
Where ? is a placeholder, that we bind by passing an array to the execute() method.
$stmt = $database->prepare("SELECT email, COUNT(*) as email_count
FROM followups
WHERE fupdate = ?
GROUP BY email");
$stmt->execute([$today]);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$email = $row["email"];
if ($row['email_count'] == 1) {
// include content A in email body
} else {
// include content B in email body
}
}
Use query with GROUP BY:
SELECT email, count(*) as email_count FROM followups WHERE fupdate='$today' GROUP BY email
In the $followup array you will have two keys: email and email_count which will show the count of current email.

selecting the rows in mysql with arrays

In my db, i have a table, Timetable where one field is Subject.
It will hold value like this. For example. 1,2,3,4
Now,
I need to compare this field with my array named
$mysubs=array('1','3','5');
I have tried this.
select * from Timetable where Subject IN (".implode(',',$mysubs).");
But if I have only one value in subject field it is working. If it holding something 1,2,3 then it is not working. Is it possible to match using 'LIKE'. Plz help me
Try some thing like this if subject field value is comma separated.
$mysubs = array('1','3','5');
$whereSubClause = '';
for($i=0; $i < count($mysubs); $i++){
$whereSubClause .= 'FIND_IN_SET($i,subject) OR ';
}
// Remove the last OR
$whereSubClasue = substr($whereSubClause,0,-3);
// now query
select * from Timetable where $whereSubClause;
But if it is not comma separated do like this:
$values = implode("','",$mysubs);
"select * from Timetable where subject IN('".$values."');"
$values = implode(',',$mysubs);
$query = "select * from Timetable where Subject IN ($values)";
I use that in some of my projects and it works well
i also thinks it is better to separate query and php operations, at least for a better code readability
Try this query
$sql = "select * from Timetable where Subject LIKE '".implode(',',$mysubs)."%'";
It may help you.
This should work:
$mysubs = array(1, 3, 5);
$sql = "SELECT * FROM Timetable WHERE Subject IN (".implode(', ', $mysubs).");";
That should output this:
$sql = "SELECT * FROM Timetable WHERE Subject IN (1, 3, 5);";
It is generally good practice in SQL to capitalize parts of the language like SELECT, INSERT, or UPDATE. Also your array of values you are searching for in $mysubs were strings, though it is better to have them as integers.
You need to save the field with appending and prepending comma.
For example:
,1,2,3,4, OR ,11,12,23,45,
And you need to search for every array element.
$mysubs=array('1','3','5');
select * from Timetable where Subject LIKE '%,1,%' OR
Subject LIKE '%,3,%' Subject LIKE '%,5,%'

Search all database with varchar and INT fields with wildcard mysql query

Trying to get a wildcard search to pick up on any text in org_name field and also to pick up any INT fields that have a 1 in them are entered into the form,
e,g If someone types Childminder in the form I want all records with the childminder INT field with a 1 in it to show up on the results...
$sql_result= "SELECT * FROM table WHERE org_name LIKE '%" . $org_name . "%'
OR carer LIKE '1'
OR childminder LIKE '1' ";
Not sure why you would do such things, but sounds like a candidate to the manual query concatenation (hint: don't do this, it hurts). PDO does not support binding column names, so you're out of luck if you're trying to have any help from libraries / other estabilished solutions.
Update
If your schema does not change and you're concerned about SQLi, you could have some matching mechanism that would take search query and array of available ("matchable") columns and process them, reporting matching columns. Then you would just make query from the safe data. Sample code:
$columns = array(/* ... */);
$query = '/* ... */';
$matches = array();
foreach($columns as $column)
{
if(preg_match('/'.$column.'/', $query))
{
$matches[] = $column;
}
}
$sqlQuery = 'you select';
foreach($matches as $match)
{
$sqlQuery .= ' OR '.$match.' = 1';
}
Not exact code, but you should get the idea.

PHP MySQL multiple id insert and set name

I've got this POST form in my website designed to make groups out of an unspecified number users. It works by while looping out all the users in my database with a check box next to their names. You tick the boxes of the users you want, give the group a name then submit the form.
To accomplish the above I need to do two queries due to the way the database has been set up. The table is called Participant/Group and it contains 3 columns: idParticipant, idGroup and GroupName. Here's what I have so far but it has its flaws:
$aParticipants = array_map('mysql_real_escape_string', $_POST['check']);
$pIn = implode("),(", $aParticipants);
$gIn = implode("', '", $aParticipants);
$query1 = mysql_query("INSERT INTO `Participant/Group` (`idParticipant`) VALUES ($pIn);");
$query2 = mysql_query("UPDATE `Participant/Group` SET GroupName = '".$_POST['group']."' WHERE idParticipant IN ('$gIn')");
So the first query inserts the id's of the users into the database and the second query adds the group name to each of those newly inserted id's. If you could combine these two queries I think it could solve all my problems but I'm pretty sure the syntax doesn't allow it.
Anyway the problem with the above code is that it overwrites the database with any subsequent overlapping queries. The important thing to remember here is users are not restricted to one group. A user with an id of 7 can be in a Group called Group A and also be in a group called Group C. There will need to be two separate rows to record this. With my code above it is creating the separate rows but both of them will have the group name of whatever was last submitted in the form.
Anyone know how my code could be tweaked (re-written if you want) to fix this?
Add group name in implode
$aParticipants = array_map('mysql_real_escape_string', $_POST['check']);
$group = mysql_real_escape_string($_POST['group']);
$pIn = implode(", {$group}),(", $aParticipants);
$query1 = mysql_query("INSERT INTO `Participant/Group` (`idParticipant`, `GroupName`) VALUES ($pIn);");
It could be done using only one query. Also, the group field must also be sanitized using mysql_real_escape_string to avoid SQL injection attacks.
$aParticipants = array_map('mysql_real_escape_string', $_POST['check']);
$group = mysql_real_escape_string($_POST['group']);
$sqlvalues = array();
foreach ($aParticipants as $p) {
$sqlvalues[] = "('$p', '$group')";
}
$values = implode(',', $sqlvalues);
mysql_query("INSERT INTO `Participant/Group` (`idParticipant`, GroupName)
VALUES $values");
For the sake of completeness, the best would be to use MySQLi or PDO to take advantage of prepared statements for the sake of performance and security.
$aParticipants = array_map('mysql_real_escape_string', $_POST['check']);
$participants = array();
foreach(aParticipants as $p) {
$participants[] = $p . ', ' . mysql_real_escape_string($_POST['group']);
}
$pIn = implode("),(", $participants);
$query1 = mysql_query("INSERT INTO `Participant/Group` (`idParticipant`, `GroupName`) VALUES ({$pIn})");
EDIT the problem here is that the $iPn string will contain ,( at the end that causes SQL error (which it did not when inserting just one value into one column).
Therefore a line
$pIn = implode("),(", $participants);
has to be replaced by
$pIn = substr(implode("),(", $participants), 0, -3);
Now it should work without any SQL errors...

How to get rest of record from one or two fields?

(Beginners question here...be gentle)
My php script is a response to a form. Assuming I have already connected to a database and extracted the post variables (just two - emailAddress and username), like so
mysql_connect('localhost', 'dbusername', 'dbpassword');
mysql_select_db('database');
extract($_REQUEST);
..and knowing that within the 'users' table, there are 'emailAddress', 'username' and 'address' fields. (The email addresses will all be unique..)
How would I search thru the table to get at the specific 'address' after receiving the emailAddress and username (and output something else if there is no name and address which matches)?
seems absurdly difficult to get an answer. this must be a very very very very very very difficult question.
Extra-special thanks to users who told me the problem was very easy, and yet couldn't come up with an answer. I salute your indefatigability, your magnificent courage, and your willingness to help.
A possible answer to my question is:
$result = mysql_query("SELECT * FROM users WHERE emailAddress='".$emailAddress."' AND username='".$username."'");
$row = mysql_fetch_array($result);
if ($row['username'] == "") {
// no results
} else if ($row['emailAddress'] == $emailAddress AND $row['username'] == $username) {
// found result
echo "The address is ".$row['address'];
} else {
// i guess something else happened
}
Be sure to tell me how this is wrong, and the real answer is easy, and yet not come up with an answer.
to get individual elements, you do "select column_name from table where criteria".
in your example it would be
select address from users where emailaddress = 'email#domain.com' and name = 'John Doe'
the column_name section can be multiple items comma seperated, so, for example, if you wanted name and address, you would do
select name, address from users where emailaddress = 'email#domain.com' and name = 'John Doe'
you have to take this sql request into a variable then execute it after that u can verify if the array is empty or not.. if it is it means that there are no combination with both that name and that email corresponding into your database.. and it's done!`$req= "Select name,address from users where emailaddress=$email and name=$name";
$result = mysql_query($req);
if !isset($result){
/// some stuffs there when everything okkay
}
else{
/// some stuffs if there is no record corresponding
}`
in vrac.. some sample exemple in the idea.. note that the sql query give the result into an array so u have to manipulate an array or hash
You can use a SELECT statement. Note this code is not safe to SQL injection.
SELECT * FROM Users WHERE emailAddress = 'someemail#gmail.com'

Categories