To trim the fat so-to-speak in my script I decided to use 1 PDO prepare to span an array of predefined tables. The PDO executes in a while loop and within the while loop there is a foreach to build the output of each result set.
This is code for a search. The script currently searches 3 tables for results (through the while iterations). We will call them tables a, b, and c. For the tested search it finds 2 results in table a, 0 in table b, and 1 in table c.
Though it finds a total of 3 results it only displays 2. One from table 'a' and one from table 'c'. The script is not building the result from the second find in the table 'a'.
I have looked it over until my eyes bleed and searched for maybe something I have wrong, I cant figure it out. Any ideas of what is wrong with this code?
// --- Build an array of places to search
$tableArray = array("services", "webPages", "dsiu");
$tableCount = count($tableArray);
$count = "0";
$resCount = "0";
$result = "";
while ($tableCount > $count) {
// -- Search tables in the array for matches
$quotedString = $db->quote($searchString);
$qSQL = "SELECT title, ldesc, SUM(MATCH(title, sdesc, ldesc) AGAINST(:string IN BOOLEAN MODE)) AS score FROM ".$tableArray[$count]." WHERE MATCH (title, sdesc, ldesc) AGAINST (:string IN BOOLEAN MODE) ORDER BY score DESC";
$q = $db->prepare($qSQL);
$q->execute(array(':string'=>$quotedString));
// -- keep a count of the results
$rowCount = $q->rowCount();
if ($rowCount > 0) {
$resCount = $resCount + $rowCount;
// -- build result html
$html = $q->fetchAll(PDO::FETCH_ASSOC);
foreach ($html as $row) {
// --- Clean the results for display
$desc = cleanURL($row['ldesc']);
$desc = str_ireplace($searchString, '<b><font color="green">'.$searchString.'</font></b>', $desc);
$desc = substr($desc, 0, 300)."...";
$result .= "<font color='red'><b>".$row['title']."</b></font><br>".$desc."<br><br>";
}
}
$count++;
}
Thanks #dan08. I added a if ($row['score'] != null) { to the foreach. Also discovered that SUM() in the query was removing what should have been results.
This is now working with the changes.
Related
I am making Tournament mod. And I do not know how to correctly do some operations with fetched array.
What my code is doing, is that it takes data from Tournament table and add it to array. Then print it in HTML table, so all users can see the place where he has.
How can I correctly get the first, second, third array data for the first 3 winners and give them a price? And how can I deal with players who have the same amount of points?
Right now the query below seems to not work too, all statements are positiv and it should execute the function.
if($counter == 1) {
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `atm` = `atm` + 20000 WHERE `id` = ".$recordRow['id_owner']." ;");
}
Sorry, my English is not good and I tried to search for the answers but didn't find anything, because i do not know for what PHP solution should i search.
My code:
$recordFetch = $GLOBALS['DATABASE']->query("SELECT *FROM `uni1_tournament` ORDER BY wons DESC;");
$counter = 0;
$RangeList = array();
while ($recordRow = $GLOBALS['DATABASE']->fetch_array($recordFetch)) {
$counter += 1;
$RangeList[] = array(
'id' => $recordRow['id_owner'],
'name' => $recordRow['name'],
'points' => $recordRow['wons']*5,
'counter' => $counter,
);
if($t_time > TIMESTAMP) {
if($counter == 1) {
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `atm` = `atm` + 20000 WHERE `id` = ".$recordRow['id_owner']." ;");
}
elseif($counter == 2) {
//to do;
} elseif($counter == 3) {
//to do;
}
}
}
Make query like this "select * from uni1_tournament GROUP BY points ORDER BY
points desc limit 3";
If you're using regular mysql or mysqli (been a while since I have for either, moved to doctrine a while back), fetch_array needs to be ran on the results and not the GLOBALS['DATABASE'] variable (guessing this a global variable for the database connection).
Try changing
while ($recordRow = $GLOBALS['DATABASE']->fetch_array($recordFetch)) {
to
while ($recordRow = $recordFetch->fetch_array()) {
In order to use your original formatting, I believe fetch_array needed to be mysqli_fetch_array instead.
i.e
while ($recordRow = $GLOBALS['DATABASE']->mysqli_fetch_array($recordFetch)) {
Hi I'm currently querying from a database base user ids for a contest, However I want to avoid choosing duplicates in my results_array, this function getrandomspecies receives a array_result, this array results iterates 7 times. How test that I don't put duplicates in my results_array? I have gotten several duplicates.
function getrandomspecies($array_result){
//database connection
$dbn = adodbConnect();
foreach($array_result as $possible){
//query the results
$querys= "select * from taxonomic_units where tsn = $possible";
$resultss = $dbn -> Execute($querys);
while($rowss=$resultss->FetchRow()){
$id = $rowss['tsn']; //there ID
$ranksss = $rowss['rank_id']; //ranking id, I choose 220 and 230
if($ranksss == 220 || $ranksss == 230){
$prelimary_array[] = $id;
}
}
//grab random index
$index = array_rand($prelimary_array,1);
//put result id into a variable
$newspecies = $prelimary_array[$index];
//put that variable in an array
$results_array[] = $newspecies; //there is 7 newspecies/winners at the end, I dont want duplicates
}
return $results_array;
}
MySQL should be the following :
select distinct tsn, rank_id from taxonomic_units where tsn = $possible
But you should ideally use prepared statements.
what about this? You may do it with one query:
$querys= "select DISTINCT tsn from taxonomic_units where tsn IN (".implode(",",$array_result).") AND rank_id IN (220,230) ORDER BY RAND() LIMIT 7 ";
Loop your result array and if it does not exists add it. If you end up with less than 7, do your big loop again.
replace this line :
$results_array[] = $newspecies;
by:
$loop_1_more_time=0;
if (isset($results_array)){
foreach($results_array as $result){
if ($result == $new_specie){
$loop_1_more_time=1;
}
}
}
if ($loop_1_more_time == 0){
$results_array[] = $newspecies;
}
//there, if $loop_1_more_time equals 1, start again. To start again and be sure you have seven instead of 6 or less, You could replace your big first "foreach" loop with a "for" loop that depends of the count() of the $array_result, and the $array_result would be array_result[$i] instead of $possible. $i would start at 0 and increment at each end of loop. It would not be incremented if $loop_1_more_time==1;.
Example :
for ($i = 0; $i < count($array_result); $i++) {
//stuff
//if ($loop_1_more_time=1;) { $i--; }
}
Why don't you try shuffling the array, and then picking the first X numbers?
That way, rather than having to check the results array for duplicates, it will never come up in the first place
I have a site developed in codeigniter where I want to retrieve comment of a specific tee.
I have a table tee like that:
- id
- user_id
- name
- created
- modified
And the table tee_comments like that:
- id
- user_id
- tee_id
- created
- modified
I have done this query:
$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified');
$this->db->from('tee');
$this->db->join('tee_comments', 'tee_comments.tee_id = tee.id','left outer');
$this->db->order_by("tee.created", "desc");
$query = $this->db->get();
With this query I retrieve two rows of tee because I have two comments in that tee.
My goal is to retrieve only one row where inside there is an array of comment like:
tee{
id,
name,
created,
modified
comment{
[0]
id,
tee_id,
comment,
created,
modified
[1]
id,
tee_id,
comment,
created,
modified
}
}
I have tried into the join:
- left
- right
- left outer
- right outer
But doesn't solve the problem, is there a way to do that?
Thanks
I love CodeIgniter! I use it constantly! You have 2 really simple options here:
One way would be to use limit.
$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified');
$this->db->join('tee_comments', 'tee_comments.tee_id = tee.id','left outer');
$this->db->order_by("tee.created", "desc");
$query = $this->db->limit(1)->get('tee');
Another way is to get first item in results Array
$query = $this->db->get();
$results = $query->result(); // gets return as an array
$row = $results[0]; // will be first row in results array
Keep in mind tho, $row will return as a object(stdClass) meaning you'll have to retrieve things from it like $row->column_name.
A handy little snippet I like to use after a call is below. It makes the row Object's Array's instead.
$results = $db->get('tee')->result(); // snippet comes after you have result array
// snippet here
foreach ($r as $k => $v) { $results[$k] = array(); foreach ($v as $kk => $vv) { $results[$k][$kk] = $vv != "NULL" ? trim($vv) : ""; } }
Use $this->db->limit(1) to retrieve a single record.
According to the accepted answer on this question, you may need to put the limit statement before the select:
$this->db->limit(1);
$this->db->select('*,tee.id as id,tee.created as created, tee_comments.id as tee_comments_id, tee_comments.created as tee_comments_created, tee_comments.modified as tee_comments_modified');
$this->db->from('tee');
Option one:
for ($i = 0; $i < count($records); $i++)
{
$data = $records[$i];
// work with date.
if($i == 1)
break;
}
Option two:
just assign the first row to var.
$row = $records['tee']['comment'][0];
Alright,
I've got a multiple select dropdown on a page called week-select, its selections get passed via ajax to my php page.
I can get the data just fine, but when the query runs it doesn't complete appropriately.
I've got this:
//Deal with Week Array
$weekFilter = $_GET['week']; /*This is fine, if it's 1 week the query works great (weeks are numbered 12-15), but if it is 2 weeks the result is formatted like this 12-13 or 13-14-15 or whichever weeks are selected*/
$weekFilter = str_replace("-",",",$weekFilter); /*This works to make it a comma separated list*/
.../*I deal with other variables here, they work fine*/
if ($weekFilter) {
$sql[] = " WK IN ( ? ) ";
$sqlarr[] = $weekFilter;
}
$query = "SELECT * FROM $tableName";
if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
$stmt = $DBH->prepare($query);
$stmt->execute($sqlarr);
$finalarray = array();
$count = $stmt->rowCount();
$finalarray['count'] = $count;
if ($count > 0) { //Check to make sure there are results
while ($result = $stmt->fetchAll()) { //If there are results - go through each one and add it to the json
$finalarray['rowdata'] = $result;
} //end While
}else if ($count == 0) { //if there are no results - set the json object to null
$emptyResult = array();
$emptyResult = "null";
$finalarray['rowdata'] = $emptyResult;
} //end if no results
If I just select one week it works great and displays the appropriate data.
If I select multiple options (say weeks 12, 14 and 15) it runs the query but only displays week 12.
When I manually input the query in SQL, how I imagine this query is getting entered - it runs and displays the appropriate data. So if I put SELECT * FROM mytablename WHERE WK IN ( 12, 14, 15 ) it gets exactly what I want.
I can't figure out why my query isn't executing properly here.
Any ideas?
**EDIT: I make the array from the multiple selections a string using javascript on the front end before it is passed to the backend.
Your resulting query with values probably looks like this with a single value in IN:
… WK IN ("12,14,15") …
Either use one placeholder for each atomic value:
if ($weekFilter) {
$values = explode(",", $weekFilter);
$sql[] = " WK IN ( " . implode(",", array_fill(0, count($values), "?")) . " ) ";
$sqlarr = array_merge($sqlarr, $values);
}
Or use FIND_IN_SET instead of IN:
$sql[] = " FIND_IN_SET(WK, ?) ";
I don't think you can bind an array to a singular ? placeholder. Usually you have to put in as many ? values as there are elements in your array.
If your HTML is correct and your week select has name="week[]", then you will get an array back with $_GET['week'];, otherwise without the [] it will only give you 1 value. Then, you're doing a string replace, but it's not a string. Instead, try this:
$weekFilter = implode(',', $_GET['week']);
I have a requirement where I need to check a pipe | in the database. If found I need to play around differently.
Here how my db table looks like //Please check the | character in row 11
And if I run a group by sql command myresult will be
Which is correct.
But my requirement is to break the | in any cell and give the count accordingly. The expected result as
Can this be done using MySQL commands alone or do I need to use some php script as well?
Any snippet will be helpful.
Hope this script might help u
$frt =array();
$stmt = $mysqli->prepare("select `fruits` from `meva`") or $mysqli->error ;
$stmt->execute();
$stmt->bind_result($fruits);
while ($stmt->fetch()) {
$frt[]=$fruits;
}
// var_dump($frt); //check all the fruits is in array
$res = array();
$tot = count($frt);
for($i=0;$i<=$tot;$i++)
{
if(preg_match("/\|/", $frt[$i]))
{
$res[] =explode( '|', $frt[$i]);
}else
{
$res[] = $frt[$i];
}
}
// var_dump($res);
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($res));
foreach($it as $v) {
$ary[]=$v;
}
$all_fruits = array();
$tot_ary = count($ary);
for($io=0;$io<=$tot_ary;$io++)
{
if(isset($ary[$io])!='')
{
$all_fruits[] = trim($ary[$io]);
}else
{
continue;
}
}
// var_dump($all_fruits);
$newArray = array_count_values($all_fruits);
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
I think you should fix your data. You can run these two statements in a row until all the data is fixed:
INSERT INTO meva (fruits)
SELECT SUBSTR(fruits, LOCATE('|', fruits) - 1) FROM meva
WHERE LOCATE('|', fruits) > 0;
UPDATE meva
SET fruits = SUBSTR(fruits, LOCATE('|', fruits) + 1)
WHERE LOCATE('|', fruits) > 0;
This will fix the table.
However, if it is your interview question (or a school assignment) just to count from the table as it is, then you can only do it if you know the maximum number of pipes in a given row.
So, if the maximum number of pipes in a row is 1, then your select statement would be:
SELECT count(*),
CASE WHEN LOCATE('|', fruits) > 0 THEN SUBSTR(fruits, LOCATE('|', fruits) - 1) ELSE fruits END
FROM meva
GROUP BY CASE WHEN LOCATE('|', fruits) > 0 THEN SUBSTR(fruits, LOCATE('|', fruits) - 1) ELSE fruits END
If you can have more than one pipe in a row, then your CASE statement will be more complex
Actually the best solution is to change your data structure. This current structure is not recommended. each 'cell' has to contain only one value. If you need to store several fuirts for a specific ID, use
id fruit
11 Apple
11 Mango
this might require some adjustments to your code / tables, but it will prevent the need for more future hacks.
You can use php and do it like below
$query = mysql_query("SELECT fruit FROM meva");
$cnt_array = array();
while($row = mysql_fetch_assoc($query)){
$fruits = $row["fruit"];
$fruit = explode("|", $fruits);
foreach($fruit as $fru){
if(array_key_exists($fru,$cnt_array)){
$cnt_array[$fru] = $cnt_array[$fru]+1;
}
else{
$cnt_array[$fru] = 1;
}
}
}
print_r($cnt_array);
NOTE : This code is not tested,please try it and edit accordingly