//First I'm assigning a $variable ($emailzipmatch) to query a database table called(repzipcodes) and having it pull and display 1 to 3 records based on matching up a customer's zip code (RepZipCode = $CustomerZipMatch) with 1 to 3 other people (GROUP BY RepId HAVING COUNT(1) <= 3") that want that customer's information from that particular zip code.
// CODE WORKS BELOW
$emailzipmatch = mysql_query("SELECT * FROM repzipcodes WHERE RepZipCode = $CustomerZipMatch GROUP BY RepId HAVING COUNT(1) <= 3") or die(mysql_error());
$recipients = array();
while($row = mysql_fetch_array($emailzipmatch))
{
$recipients[] = $row['RepEmail'];
echo "Agent's Email Address: ";
echo 'font color="#FF7600"',$row['RepEmail'], '/font';
echo '<br />';
echo "Rep's ID: ";
echo '<br />';
echo 'font color="#FF7600"',$row['RepId'], '/font';
echo '<br />';
echo 'hr align="left" width="50%" size="2" /';
}
//MY PROBLEM BELOW
// For the NEXT step of the process above I would take $row['RepEmail'] and $row['RepId'] which can have 1 to 3 results and assign the 1 to 3 results a new $variable so it can be inserted into a different db table so I can track the results of the query ($emailzipmatch = ) from the top of the page: ie..
<New Variable> <Listed from above>
$SentRepId 0 = RepId (results from above echo area)
$SentRepId 1 = RepId (results from above echo area)
$SentRepId 2 = RepId (results from above echo area)
// Below I'd like to insert the above results into a new database
$?Variable??? = mysql_query("INSERT INTO sentemail
(SentRepId0, SentRepId1, SentRepId2,SentDateTime
) VALUES (
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
NOW()
)") or die(mysql_error());
//Thank ahead of time for any help you guys can give me. Please respond with ANY question if my coding or request isn't clear or if I've been confusing due to my lack of experience with PHP and MySQL.
I think I know what you are going for here. I have done something similar before where I needed to keep a record for a while so I gave each search result an id on output and placed them in separate rows of a table along with a time stamp so it could be cleaned up at a later time or if you wish to search by time (mysql has a timestamp of it's own also but that's another thing to look in to if you haven't already)
So to make a 'log table' for example you might want to design something that works like the following:
<?php
$search_id = md5(uniqid()).rand(100,999); //// MAKE AN ID FOR THE SEARCH;
$timestamp = time(); // IN CASE YOU WANT TO CLEAN UP AT A LATER DATE, MUST BE AN INTEGER IN MYSQL (so you can use a less than $timestamp in the delete query)
$emailzipmatch = mysql_query("SELECT * FROM repzipcodes WHERE RepZipCode = $CustomerZipMatch GROUP BY RepId HAVING COUNT(1) <= 3") or die(mysql_error()); // if you are just wanting to limit the results look at LIMIT in a mysql tutorial somewhere.
$recipients = array();
while($row = mysql_fetch_array($emailzipmatch))
{
//// THE REST OF YOUR CODE HERE (and at the end of the while loop insert in to a table, in your case 'sentemail')
mysql_query("INSERT INTO sentemail (search_id, rep_email, rep_id, zip_code, timestamp) VALUES ('$search_id', '{$row['RepEmail']}', '{$row['RepId']}', $CustomerZipMatch, $timestamp);") or die(mysql_error()); // or what ever details you are after
}
?>
This should leave you with a reference table that you can search for by different criteria. Not the most perfect way of doing it but it will get the job done.
Hope that gives you a different perspective on it :)
In regards to "due to my lack of experience with PHP": As you develop your skills, and you will I'm sure, take some time to look at Object Oriented PHP in the future. For more server heavy or complicated things it can be worth knowing. I'm saying this to you now because I wish someone had told me earlier.
Good luck.
As long as you have user access, you can do:
$?Variable??? = mysql_query("INSERT INTO db1.sentemail (SentRepId0, SentRepId1,SentRepId2,SentDateTime) VALUES (
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', // ?????
'$_SESSION[RepId]', NOW())") or die(mysql_error());
Related
Hi buddies :) I was required to create a php code to handle some workers' data stored in DB. I got the desired result but it takes seconds and seconds (seconds and seconds! >.<) to finish, so I'm afraid I'm not doing something in a right way :(
The workers' data is stored in a mysql table (table1), something like this:
I'm given a pair of dates: initial_date (a) and final_date (b), so my goal is to copy the given workers' data in a new table (table2), day by day from a to b. The expected table should be as shown below (this table will be used later as a basis for further operations, which is not part of the question)
It's a requirement to overwrite any existing data between a and b dates, and 'jump' weekends and holidays.
To get my goal, I'm coding this (let's assume that the connection and all that is done and the checkworkingday function is given):
$initialdate = '2016-10-10';
$finaldate = '2016-10-12';
$x = $initialdate;
do {
if (checkworkingday($x) == true) {
$query = mysqli_query($connection,"SELECT name,task FROM table1");
while($row = mysqli_fetch_array($query)) {
$task = $row['task'];
$worker = $row['name'];
$query2 = mysqli_query($connection,"SELECT task FROM table2 WHERE name = '$worker' AND date = '$x'");
$row2 = mysqli_fetch_array($query2);
$existingtask = $row2['task'];
if (!isset($existingtask)) {
mysqli_query($connection,"INSERT INTO table2 (date,name,task) VALUES('".$x."','".$worker."','".$task."')");
} else {
mysqli_query($connection,"UPDATE table2 SET task = '".$task."' WHERE date = '".$x."' AND worker = '".$name."'");
}
}
}
$x = date('Y-m-d', strtotime($x . "+1 day"));
} while ($x <= $finaldate);
Just for 3 days as shown in the example, it takes a long to end; and for several weeks or months it takes very, very long (even max execution time is exceeded depending on dates range!).
I'm a newbie and I know the code is quite 'rustic', but I've revised and checked the code and info out there without getting a better performance. What am I doing wrong? Thanks :)
Instead of looping through the enitre data, try INSERT.. SELECT :
INSERT INTO table2 (date,name,task)
SELECT date,name,task
FROM Table1
WHERE < >;
i am trying to create a golf tourney scoreboard where i input the scores from each round and if i put in what course was played, it will go into the row of my sql database. how do i make a total score that is figured out in my php code go into a row that i specify on the form?
the form is built out like this:
<input name='name/handi/par/course/hole1/etc' type='text'>
to save space/time just short-handing the coding as much as possible. the php looks like this:
$name = $_POST['name/handi/par/course/hole1/etc'];
then i have the math broken out to figure the front 9, back 9, total score (with handicap [handi] worked in)
$totOut = ($hole1 + $hole2...etc)
$totIn = ($hole10 + $hole11 ... etc)
$total = ($totOut + $totIn) - $handi;
$o_u_total = $total - $par; (over/under for the week)
$o_u_today = $total - $par; (over/under for the day)
the total for today (b/c there are 4 rounds) and the total for the whole week. the totals for the whole week are worked out in a query on the display page:
$sql = "SELECT name,
SUM(total) AS Score,
SUM(o_u_total) AS Over_Under,
total AS Total_Today,
o_u_today AS Over_Under_Today
FROM matchplay
GROUP BY name
ORDER BY Score ASC";
$result = mysqli_query($conn, $sql);
and how i am trying to make the inputted value (course name) go into the specific row (designated in my sql dbase) is like this:
$ridge;
if ($_POST['course'] = 'The Ridge') {
($ridge = $total);
}
$cove;
if ($_POST['course'] = 'The Cove') {
($cove = $total);
} etc
i have a feeling that i am doing something terribly wrong with the if/else, but i don't know how else to choose what i want the $total to go into.
can anybody help me?
i figured it out ... thanks if anybody saw it and was in the middle of thumping me on the head with how easy it was
$ridge;
if ($_POST['course'] == 'The Ridge') {
($ridge = $total);
}
and not
$ridge;
if ($_POST['course'] = 'The Ridge') {
($ridge = $total);
}
Glad you did figure it out. To enhance your code and avoid multiple ifs, you can use a switch case statement.
$course_name = $_POST['course'];
switch($course_name){
case ('The Ridge'):
// your code here
break;
case ('The code'):
// an other code here
break;
}
Hope this help.
I'm quite new to php and mysql so forgive me if I'm doing this completely wrong. I am making a printing balance application and the code below is a part of it.
$command="SELECT itemname FROM items";
$results = mysql_query($command);
while($row = mysql_fetch_assoc($results))
{
foreach ($row as $key => $value) {
print "<input type='radio' name='itemtype' value='$value'>".$value."</input><br />";
}
}
This here is supposedly the price printing form where the user chooses between SHORT BOND PAPER and LONG BOND PAPER (the column itemname from items). The options appear as radio buttons. It works but now I'm stuck with the issue of being able to fetch the price as inserted in their respective rows. Since the itemname and their price are all user-inputted into the database, I'm not supposed to declare their specific price into the code itself, and should be able to retrieve it from the database. I want to be able to get the prices based on the item chosen by the user once they click submit, because I'd need to do this to compute for the price of printing when multiplied with the number of pages later.
I think it's definitely possible but I'm not quite sure how. Theoretically, it would be along the lines of SELECT itemprice FROM items WHERE itemname = $value but ha, I don't think it works that way.
solution edit: here's the complete solution for reference. $compute is just a sample to test if it works while 5 is a sample number of pages that would be entered.
if ($command = mysql_query("SELECT `itemprice` FROM `items` WHERE `itemname` LIKE '" . mysql_escape_string($_POST['itemtype']) . "'"))
{
while($row = mysql_fetch_assoc($command))
{
$compute = $row['itemprice'] * 5;
echo $compute;
}
}
else
{
echo (mysql_error ());
}
It would be something like that indeed.
SELECT itemprice FROM items WHERE itemname = $_POST['itemtype']
assuming that itemprice is the actuial colum of the price. HOwever, doing it like this, makes your code vulnerable to mysql injections. So before you contine, consider reading up a little.
I'm creating a small project with PHP/MYSQL but i can't get my query working the way i need it. I have 2 tables
Table 1 (char):
Id, name.
Table 2 (spells):
Id, char, spell_name.
I'm getting the output:
Name Spell1
Name Spell2
Name Spell3
But I need it to be:
Name Spell1
Spell2
Spell3
Here's my query:
$query = "SELECT char.name AS name, spells.spell_name AS spell
FROM char, spells
WHERE (char.id = spells.spell_name)";
Any ideas?
I think you're gonna have to first get the ID of the character to query, and then pull the spells s/he has access to. Example:
$char_id = 0; // value would be assigned arbitrarily.
$query = "SELECT *
FROM 'spells' s
WHERE s.char = $char_id;";
$result = $pdo->query($query);
while($row = $result->fetchObj()){
// do something with the spells obj here
}
With SQL, you need to grab full rows at a time, so I believe the situation you want isn't possible.
As Goldentoa11 wrote. Make two selects, or create query with two result sets (more selects in one command), or accept current state (is normal and you can verify data consistency). I prefer current state, but sometimes use any of described solution (based on query frequency, size of result etc.).
If you need to list such data, you can than use something like this:
$currentName = null;
while ($row = mysql_fetch_object($result))
{
if ($currentName != $row->name)
{
echo "<b>" . $row->name . "</b><br />";
$currentName = $row->name;
}
echo $row->spell_name . "<br />";
}
Hello and thanks in advance to anyone that can answer my question. I'm still a bit green in terms of PHP but I will try to explain what I want and what my problem is.
I have 3 arrays with MySQL query's results:
$resultsTextPageID (with pageID value [int(10)])
$resultsTextPageName (with pageName value [text])
$resultsTextIntro (with pageIntro value [text])
I would like the final output to be
<b>[pageName goes here]</b><br />
[pageIntro goes here]<br /><br />
Like this:
[pageName]
[pageIntro]
[pageName]
[pageIntro]
I tried the following code:
//ECHO PAGEID PART
while ($pageID = mysql_fetch_assoc($resultsTextPageID))
{
echo '<b><a href="page.php?id='.$pageID['pageID'].'">';
//ECHO PAGENAME PART
while ($pageName = mysql_fetch_assoc($resultsTextPageName))
{
echo $pageName['pageName'].'</a></b><br />';
//ECHO PAGEINTRO PART
while ($intro = mysql_fetch_assoc($resultsTextIntro))
{
echo $intro['pageIntro'].'<br /><br />';
}
}
}
But the output I get is:
[pageName]
[pageIntro]
[pageIntro]
[pageName]
I think the problem is on the way I structured the while loops, but for the life of me, I can't figure out how to fix it.
Can someone help me? Again, thanks in advance! :D
EDIT 1:
Here is the query code:
//Prepare and set search query string
$q = preg_replace("/[^a-zA-Z0-9 !?.:]+/", " ", $_GET['q']);
//RETRIEVE KEYWORDS
//seperate multiple keywords into array
$keywords = explode(" ", $q);
//Clean empty arrays so they don’t get every row as result
$keywords = array_diff($keywords, array(""));
//MySQL QUERY
$searchTextPageID = "SELECT pageID FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";
$searchTextPageName = "SELECT pageName FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";
$searchTextIntro = "SELECT pageIntro FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";
Essentilally you should be collecting all 3 pieces of info at one time, if these are all in the same table, the job is quite easy.
$qry = "select pageID, pageName, pageIntro from <your table name>";
// now loop thru results
while ($page = mysql_fetch_assoc($qry))
{
echo '<b><a href="page.php?id='.$page['pageID'].'">';
echo $page['pageName'].'</a></b><p>';
echo $page['pageIntro'].'<br /></p>';
}
If the data is spread over more than one table you will have to do a JOIN in your sql.
Your code doesn´t make much sense since you iterate over every entry of $resultsTextPageID but already in the first entry you iterate over all $resultsTextPageName. Therefore the second time you enter the body of resultsTextPageID-loop there is no more to fetch from $resultsTextPageName. This happens the exact same way to the second/third while-loop.
Assuming you have only one title and only one page intro you can change your code to
while ($pageID = mysql_fetch_assoc($resultsTextPageID))
{
/* get only ONE entry */
$pageName = mysql_fetch_assoc($resultsTextPageName);
$intro = mysql_fetch_assoc($resultsTextIntro);
echo '<b><a href="page.php?id='.$pageID['pageID'].'">';
echo $pageName['pageName'].'</a></b><br />';
echo $intro['pageIntro'].'<br /><br />';
}
But that is in no way nice code.
You should take a look at mysql JOIN commands to arrange your data correctly in the database select. Then your output code would be much easier.
EDIT because you added mysql-code:
you are selecting 3 times from the same db under the same condition, only to retrieve different columns, change it to
$searchTextPageID = "SELECT pageIDm, pageName, pageIntro FROM pages WHERE pageIntro LIKE '%".$keywords[$i]."%' OR pageText LIKE '%".$keywords[$i]."%'";