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]."%'";
Related
I'm developing an app about books and I had a table for contents. before, I made a mistake and I split content in myself and insert them in database. after inserting 90 books I had 1000 records and I found out that it was wrong. Now, I create a table of content and I insert all content of every books(every book has a record), so I want to split content with character(*).
but it doesn't work.
It is my Previous code:
$sql2 = "SELECT tblcontent.content
from tblcontent,tblstory
where tblcontent.storyid=tblstory.storyid
and tblcontent.storyid='$storyid'";
$r2 = #mysqli_query($dbLink,$sql2);
$result2 = array();
while($res2 = #mysqli_fetch_assoc($r2))
{
$result2[] = $res2;
}
and I've added this code:
$result2=explode("*",$result2);
and
if(isset($result2)){
echo json_encode(array("result2"=>$result2));
}
But it doesn't work.Thanks in advance
So my problem is this I got a code that loops trough a loggfile then compares them to a treestructure and then gives them a id that correspond to the id in the structure. To not get a lot of bad traffic i sort out all the 302 and above.
The problem is now that i want some specific 302s to count that have a particular pagetype in the structure. This is not a big problem as I can just match the url in the loggfile against the url in the tree structure but some loggfiles does not use friendly url while the structure is in friendly url this creates a problem but I can just match the id in the query parameter with the id in the structure. I then make a string of all the ids that match the special pagetype that I want.
The problem is this I can not get the Mysql statement to work, it looks like this.
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN '$check'";
A example query can look like this "id=4&epslanguage=sv" so I want to check only the id=X part.
It´s a kinda easy question really im just stuck and can not get it to work, any help is appreciated!
I think your Q is: How do I extract id from that part of a line?
".. so I want to check only the id=X part."
Once you have isolated that string then you can use:
$string = "id=4&abclang=sv";
parse_str($string);
echo $id; // 4
EDIT
In light of other responses:
$strings[] = "id=4&abclang=sv";
$strings[] = "id=45&abclang=en";
$vals = array();
foreach( $strings as $string){
parse_str($string);
$vals[] = $id ;
}
$in_clause = join(",", $vals) ;
$sql = "SELECT lid FROM logfile WHERE something IN ($in_clause) ";
echo $sql; // SELECT lid FROM logfile WHERE something IN (4,45)
So you have the IDs already and want to filter the MySQL query to just get these rows?
$check = Array(1, 2, 3, 4);
$check = implode(",", $check);
$sqlQ1 = "SELECT `lid` FROM logfile WHERE date = '$date' AND ´query´ IN ($check)";
This question is quite simple but I'm not sure of the terms involved to look up the answer myself. What I have is a MYSQL database containing all of my product information. I would like to make an image appear on the product pages for products that have a certain attribute. I have created this SQL query which outputs the list of product_ids for the products that I would like the image to show up on. However, I do not know how to use this set of results in the page itself.
I currently have:
$cupwinnerids = mysql_query("SELECT product_id FROM `jos_vm_product_type_1` WHERE jos_vm_product_type_1.Cup_Winner ='Cup Winners';");
while($row = mysql_fetch_array($cupwinnerids))
{
echo $row['product_id'] . ",";
}
This outputs the correct ids with a comma in between them. What I would like to do is wrap the whole thing with something like $listofids = (...) and then I can use in the product page PHP file: if $product_id is in $listofids then ... if not then ... I am just having a problem understanding how to use this selection of ids. If I try to output the list directly I just get "array". Any help would be greatly appreciated.
The problem may be that you are trying to display the array using echo, while you should use print_r.
In your case you could do something like this:
$listofids = array();
$cupwinnerids = mysql_query("SELECT product_id FROM `jos_vm_product_type_1` WHERE jos_vm_product_type_1.Cup_Winner ='Cup Winners';");
while($row = mysql_fetch_array($cupwinnerids))
{
array_push($listofids, $row['product_id']);
}
print_r($listofids);
As Ryan commented, if you want to manage the values of the array you should then use a foreach loop, that iterates through the array, something like this
foreach ($listofids as $id) {
echo $id . ", ";
}
// EDIT: you could also use echo implode($listofids,", ") which will do basically the same
If what you want is to compare if $product_id is in $listofids us in_array, that returns true if the value you are looking for is in the array, and false if it isn't:
if (in_array($product_id, $listofids)) {
echo "Product ID is in the List of Product ID's";
}
else {
echo "Product ID isn't in the List of Product ID's";
}
Why not return $cupwinnerids to your products page, and then do something like...
while($row = mysql_fetch_array($cupwinnerids)) {
if ($row['product_id'] == $product_id)
// display your image
}
It sounds like you would be better off modifying your query for returning the products so that it joins to the jos_vm_product_type_1 table -
SELECT `jos_vm_product`.*, IF(`jos_vm_product_type_1`.`product_id` IS NULL, 0, 1) AS `winner`
FROM `jos_vm_product`
LEFT JOIN `jos_vm_product_type_1`
ON `jos_vm_product`.`product_id` = `jos_vm_product_type_1`.`product_id`
AND `jos_vm_product_type_1`.`Cup_Winner` ='Cup Winners'
//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());
At this time I have this very complex query that I loop through and I get something like this:
List of Challenges:
TEAM A
- Challenge 1
TEAM A
- Challenge 4
TEAM A
- Challege 6
And I want to change to something like:
TEAM A
- Challenge 1
- Challenge 4
- Challenge 6
My question is, since the query is a very complex one, maybe I could do this inside the loop but, if that's the case, how can we achieve something like that?
Can I ask an example case so that I can use, in order to solve this issue?
Thanks a lot,
MEM
UPDATE:
The query is something like this:
Translated:
public function listachallengesPendentes()
{
$select = $this->getAdapter()->select();
$select->from(array("e"=>"teams"),array('name'));
$select->join(array("de"=>"challengeperteam"),"e.cod_team = de.cod_teamFk",array());
$select->join(array("d"=>"challenges"),"d.cod_challenge = de.cod_challengeFk",array('title'));
$select->columns(array("e.cod_team"
,"name_team"=>"e.name"
,"d.cod_challenge"
,"name_challenge"=>"d.title"
,"d.details"
,"d.score"
,"category"=>"d.cod_categoryFk"
,"de.proof"
,"de.date_concluded"
,"de.cod_challenge_team"
));
$select->where("de.status = 0");
$select->order(array('e.cod_team DESC', 'de.cod_challenge_team DESC'));
return $this->getAdapter()->fetchAll($select);
}
So I need to add a distinct some part :s :D ?
The foreach actually is pretty basic:
foreach ($challenges as $d){
//display the name:
echo $d['name_team'];
...
}
UPDATE 2
The clean query (not tested):
SELECT e.name
,d.cod_team
,d.cod_challenge
,d.title
,d.details
,d.score
,de.proof
,de.date_concluded
,de.cod_challenge_team
FROM teams e
INNER JOIN challengeperteam de ON de.cod_teamFk = e.cod_team
INNER JOIN challenges d ON d.cod_challenge = de.cod_challengeFk
WHERE de.status = 0
ORDER BY e.cod_team DESC, de.cod_challenge_team DESC;
Something along the lines of:
$current_team = null;
foreach($challenges as $challenge){
if($current_team != $challenge->team){
$current_team = $challenge->team;
echo $current_team, "\n";
}
echo $challenge->challenge_name, "\n";
}
At a very basic level, ie in the loop, you can just detect if the TEAM A variable is equal to the current (previous) value, and if so, don't print it a second time. This relies on the result set being sorted on the TEAM A column.
However, you can also do this in the SQL query, so if you can provide the current SQL Query, I can explain how you'd update it.
you could store the array results in a multi-dimensional array like so:
$query_Challenges = "SELECT `Team`,`Challenges` FROM YourTable";
$Challenges = mysql_query($query_Challenges, $dbconnection) or die(mysql_error());
$row_Challenges = mysql_fetch_assoc($Challenges);
$challengeResults = array();
do{
if(!array_key_exists($row_Challenges['cod_team'])){
$challengeResults[$row_Challenges['cod_team']] = array();
}
$challengeResults[$row_Challenges['cod_team']][] = $row_Challenges['cod_challenge_team'];
}while($row_Challenges = mysql_fetch_assoc($Challenges));
EDIT
looking at your query statement, the data should be already sorted properly by your ORDER clause, so if you just need not repeatedly print the team as shown in codeblock 2, then something like:
$team = '';
do {
if($team != $row_Challenges['cod_team']){
echo "TEAM $row_Challenges['cod_team']<br/>";
$team = $row_Challenges['cod_team'];
}
echo " - $row_Challenges['cod_challenge_team']<br />";
}while($row_Challenges = mysql_fetch_assoc($Challenges));
you could easily substitute a foreach for the do loop, as long as there is a variable used as the "current team" and an if statement used to say "dont print the next team name unless its different than the current team name"