How can I avoid duplicate return data with MYSQL with autosuggest with this code?
Thank you so much for helping
<?php
include('conn.php');
$str = strtolower($_GET['content']);
if(strlen($str))
{
$sel = mysql_query("select * from Streams where title like '".trim($str)."%'");
if(mysql_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysql_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysql_fetch_array($sel))
{
$country = str_ireplace($str,"<b>".$str."</b>",($row['title']));
echo "<tr id=\"word".$row['title']."\" onmouseover=\"highlight(1,'".$row['title']."');\" onmouseout=\"highlight(0,'".$row['title']."');\" onClick=\"display('".$row['title']."');\" >\n<td>".$country."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
What I can see in your code is that there is only a single field - title - from the SQL resultset that you are using in the PHP code. So why not instead write your query as:
"SELECT DISTINCT `title`
FROM Streams
WHERE title like '".trim($str)."%'"
Or perhaps if you can't change the query, you may store the title in a PHP array and then run array_unique on it to avoid duplicates before writing them to HTML.
From looking at your code, it seems like you're only using the "title" field from your database. You could do this:
$sel = mysql_query("SELECT DISTINCT title FROM Streams WHERE title LIKE '".mysql_real_escape_string(trim($str))."%'");
As per the MySQL documentation:
The [...] DISTINCT options specify
whether duplicate rows should be
returned. [...] DISTINCT specifies
removal of duplicate rows from the
result set. It is an error to specify
both options.
Ideally you need to select distinct elements
mysql_query("SELECT DISTINCT(title) FROM Streams WHERE title LIKE '".mysql_real_escape_string(trim($str))."%'");
Ofcourse if any reason you cant do that,
Put the data in a array and check if it was previously added to prevent duplication, define array outside the while
$data = array()
if (!in_array($row["title"], $data)){
\\do your thing
array_push($data, $row["title");
}
Related
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
I'll try to be as specific as possible.
I have a database table from which I'm going to print information. The easiest way to do this is by doing something like this:
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result))
echo $row['column_to_echo'];
}
mysqli_close($con);
If this query returned one row, with an address, the outcome on the screen would be something like this "My street 14" Right? And that's how it works as well. So that's great. Exactly what I want.
HOWEVER:
I need to have these SQL queries in functions, because the queries are dynamic based on who's loading the page.
So a function like that looks something like this;
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result)) {
return $row['column_to_echo'];
}
mysqli_close($con);
}
And I use it by doing this:
<?php $address = getUserAddress(current_user_id); echo $address; ?>
So in this case, we can safely assume that the string being returned by the function is the same string as used in my first example, right? (given the correct ID is being sent into the function).
This is NOT the case.. I would only get the first word on my screen. Meaning the function isn't returning the full string, and I have no idea why.
On my screen it would appear as "My", instead of "My street 14". And that is my problem.
Does anyone have any clue as to why this is happening?
Rewrite your function like this
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT * FROM table blabla");
while($row = mysqli_fetch_array($users_result)) {
$str.=$row['column_to_echo']." ";
}
mysqli_close($con);
return($str);
}
Problem :
You were actually making use of a return inside the while loop which just returned the first value.
Try this instead:
function getUserAddress($userid)
{
$con=mysqli_connect("server","user","pass","dbname");
$users_result = mysqli_query($con,"SELECT `column` FROM table blabla");
$row = mysqli_fetch_row($users_result)
mysqli_close($con);
return $row;
}
Let me know if that works.
I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;
Im creating a website, where I make a foreach, that echos out some groups, containing checkboxes, with values and names. At the moment that data comes from a multidimensional array, but writing that array when adding new items, is slow, and not very user-friendly.
At the moment, my foreach looks like this:
echo '<form method="post" action="'.$_SERVER['PHP_SELF'].'">';
/* NEXT WE CREATE OUR FOREACH LOOPS TO ECHO THE HTML FOR LOOKS AND CHECKBOXES */
$totalID=0; // this is a counter we use to build our check box names
foreach ($items as $list){
$totalID++; // add one to the checkbox name counter
echo "<h2>{$list['title']}</h2>\n"; // and echo out our section header
foreach ($list['items'] as $cbox){ // now for each item in the list, call it $cbox
// $cbox now holds the item name, and point value
echo "<label class='checkbox'><input type='checkbox' name='totals[$totalID][]' value='{$cbox[1]}'> {$cbox[0]}</label>\n";
}
}
echo "</form>";
And my array I write is something like this:
$items['computers']['title']='Computer Brand';
$items['computers']['items'][]=array('Apple iMac',1);
$items['computers']['items'][]=array('Apple Macbook',.5);
$items['phones']['title']='Phone Brand';
$items['phones']['items'][]=array('iPhone',1);
$items['phones']['items'][]=array('HTC',1);
As said, I can write this, but takes time.
I want to get it into a database, that data above, but I'm having problems about echo'ing it out, I really can't see how I should do.
My current database looks like this:
http://i.stack.imgur.com/Rj0wQ.png
Anyone that have some tips how to do this easy, and also do it user friendly?
Thank you!
$sql = "SELECT category, title, brand, point FROM yourtable ORDER BY category, title";
$result = mysql_query($sql);
$data = array();
while(list($category, $title, $brand, $point) = mysql_fetch_array($result)) {
if (!isset($data[$category])) {
$data[$category] = array();
}
if (!isset($data[$category]['title'] && (!empty($title)) {
$data[$category]['title'] = $title;
}
if (!isset($data[$category]['items'])) {
$data[$category]['items'] = array();
}
$data[$category]['itemps'][] = array($brand, $point);
}
Your table is just screaming for some normalization, however. It's a horrendous construct.
Well if you dont' want to parse your result into a multi-dimensionnal array like you did before which would be the easiest task but you have to double de CPU work, there is one way i use often in this case:
No1: Make sure your result is sorted by "Category" and then sorted by whatever criteria you want to order your answers as.
No2: Initialize the "$current_category" to NULL
No3: Loop and detect new $categories and output the header as you go. Your script will look like this:
$currentcategory = NULL;
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
//Check for a category change
if($currentcategory != $row['category']){
echo '<h2>'.$row['title'].'</h2>'.PHP_EOL;
$currentcategory = $row['category'];
}
//Output the label
echo '<label class="checkbox"><input type="checkbox" name="totals'.$row['id'].' value="'.$row['point']'."> '.$row['brand'].'</label>'.PHP_EOL;
}
sorry my code is a bit long, please bear with me. i am trying to load the link stored inside a cell from my sql table via php. The user is able to click a checkbox and choose which link to load. however, what i have is a bit off. it loads all the links present in the sql table instead of the one the user chooses. what did i do wrong? please guide. Thank you!
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
$xml = simplexml_load_file($row['bclink']);
}
}
and the HTML is like
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $row['id']; ?>">
OK, a new try with the additional information you gave:
This solution is based on the following assumptions:
The value of the checkboxes you get is in some way related to a field in the database
For the sake of simplicity, I have named that field id - it can be named differently in the database, but only you would know that...
That being said:
$sql = "SELECT * FROM previousbroadcast ORDER BY id DESC";
$result=mysql_query($sql);
$count = mysql_num_rows($result);
// in this array, we now have all the values of the checkboxes the user selected
$checkboxvalues = $_REQUEST['checkbox'];
while ($row = mysql_fetch_assoc($result)) {
if (isset($_POST['re_b'])){
// if the ID of this row is mentioned in the checkboxes the user clicked
// then - and only then - load the file
if (in_array($row[id], $checkboxvalues)) {
$xml = simplexml_load_file($row['bclink']);
}
}
}
ok, your code didn't come quite well, it's incomplete.
but for what I can see the $del_record value is the checkbox array with key $i
problem there is that you are calling the database every time, so it's easy to get lost.
you should store the fetched arrays in another array and then iterate there, instead of making lots of requests to the database, that will make your code run faster and you will have more control over it.
I would get SQL to do all the filtering for you:
if (isset($_POST['re_b'])) {
$checkboxvalues = isset($_REQUEST['checkbox']) ? $_REQUEST['checkbox'] : array();
$myCheckboxes = array();
foreach ($checkboxvalues as $cbv) {
$myCheckboxes[] = mysql_real_escape_string($cbv);
}
$sql = "SELECT * FROM previousbroadcast WHERE id IN ('" . implode(",", $myCheckboxes) . "') ORDER BY id DESC";
$result=mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$xml = simplexml_load_file($row['bclink']);
// do something here with $xml or it will get overwritten
}
}