Why doesn't my query work for retrieving substrings? - php

Below is my query to show user comments. It works well:
enter
$query='SELECT
customers.cust_id,
customers.f_name,
customers.l_name,
user_comments.comment_txt,
clubs.name_club
from
customers
inner join
user_comments
on customers.cust_id = user_comments.cust_id
inner join
clubs
on user_comments.cust_id = clubs.cust_id
ORDER BY RAND() LIMIT 1,1
';
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$nameclub =$row['name_club'];
$comment =$row['comment_txt'];
echo '<div><img src="images/arrow.gif"> Name : '.$nameclub.'</div>';
echo '<div>'.$comment.'</div><br>';
echo '<div>'.$row['f_name'].' '.$row['l_name'].'</div>';
}
echo '<p style="text-align: left"> Show all comments</ ></p> '; ?>
I now want to show just about 100 characters of a user comment. So I changed my query accordingly, but it does not work:
enter $query='SELECT
customers.cust_id,
customers.f_name,
customers.l_name,
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
clubs.name_club
from
customers
inner join
user_comments
on customers.cust_id = user_comments.cust_id
inner join
clubs
on user_comments.cust_id = clubs.cust_id
ORDER BY RAND() LIMIT 1,1
';
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$nameclub =$row['name_club'];
$comment =$row['comment_txt'];
echo '<div><img src="images/arrow.gif"> Name : '.$nameclub.'</div>';
echo '<div>'.$comment.'</div><br>';
echo '<div>'.$row['f_name'].' '.$row['l_name'].'</div>';
}
echo '<p style="text-align: left"> Show all comments</ ></p> '; ?>
How can I fix my query to just get 100 characters of a comment?

You're using SUBSTR() incorrectly. Replace this:
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
With this:
SUBSTR(user_comments.comment_txt,1,100) as comment_txt,
Edit per comment: to add ... if the text continues past 100 characters, use
CONCAT(SUBSTR(user_comments.comment_txt,1,100), IF(LEN(user_comments.comment_txt) > 100, '...', '')) as comment_txt,

Try this
Replace this
user_comments.comment_txt.substr(comment_txt,1,100) as comment_txt,
To
SUBSTRING(user_comments.comment_txt,1,100) as comment_txt,
Mysql function_substring

Another solution is to use a php function that cuts a string into a number of words:
<?php
function cut_string($string_to_cut, $number_words, $append = "...") {
$string = array();
$string_return = "";
$return_string = "";
$string = explode(" ", $string_to_cut);
if(count($string) < $number_words) {
for($x=0; $x < count($string); $x++) {
$string_return .= $string[$x] . " ";
}
$return_string = substr($string_return, 0, -1);
}
else {
for($x=0; $x < $number_words; $x++) {
$string_return .= $string[$x] . " ";
}
$string = substr($string_return, 0, -1);
$return_string = $string . $append;
}
return($return_string);
}
?>
Note: This is word count based, not character count based.

Related

how to retrieve the table values from database using mysql php

I have concatenated three tables to one table that is edit all. Now i'm going to retrieve the all the 4 values that starts with the particular letter, But is displaying all values with starts with different letter.
include "config.php";
$term = strip_tags(substr($_POST['searchit'],0,100));
$term = mysql_real_escape_string($term);
if($term=="")
echo "Enter Something to search";
else{
$query = mysql_query("select distinct videoname,category,name,email from edit_all
where videoname like '$term%' or category like '$term%' or name like '$term%' or email like '$term%'limit 1") or die(mysql_error());
$string= '';
if (mysql_num_rows($query))
{
while($row = mysql_fetch_assoc($query)){
$string .= "<b><a href='#'>".$row['videoname']."</a></b> -<br> ";
$string .= $row['category']."-<br>";
$string .= $row['name']."-<br>";
$string .= $row['email']."-<br>";
$string .= "\n";
}
}
else{
$string = "No matches found!";
}
echo $string;
}
?>

php how to limit the result

i have that code, and i want to limit the result to 10 max.
how can i do that?
<?php
$actors = rtrim($movie_info[0]->actors, ", ");
if(stristr($actors, ",")) {
$actors = explode(",", $actors);
array_walk($actors, 'add_url_on_tags', '/actor');
echo ul($actors, array("class" => "genres2"));
echo '<div style="clear:both;"></div>';
}elseif(!empty($actors)) {
echo ''.$actors.'<br />';
}else{
echo 'empty';
}
?>
thank for your help!
What you're looking for is $actors = array_slice($actors, 0, 10);
<?php
$actors = rtrim($movie_info[0]->actors, ", ");
if(stristr($actors, ",")) {
$actors = explode(",", $actors);
$actors = array_slice($actors, 0, 10);
array_walk($actors, 'add_url_on_tags', '/actor');
echo ul($actors, array("class" => "genres2"));
echo '<div style="clear:both;"></div>';
} elseif(!empty($actors)) {
echo ''.$actors.'<br />';
} else{
echo 'empty';
}
?>
you should probably do it in your SQL instead of only cherry picking your results via the code above.
select
*
from
yourTable
where
someColumn=SomeCondition
order by
someColumn
limit 10
^^ This is the clause to add.
Will only bring back the first ten results
you can then use it for pagination, by adding one more value like this:
limit 10,10
This will now bring back ten results, but skip the first ten (basically showing results 11-20

How to add a seperator between menu items in PHP but not on the end

I'm trying to put an image as a separator between menu items but not on the outside and I'm not sure how to do this.. So it would end up being something like this:
HOME | ABOUT | CONTACT
unfortunately my code puts one after every entry including the last one.
mysql_select_db($database_db_connection, $db_connection);
$query_rsMenu = "SELECT * FROM menu WHERE online = 1 ORDER BY position ASC";
$rsMenu = mysql_query($query_rsMenu, $db_connection) or die(mysql_error());
echo "<ul class='MenuBarVertical'>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu)) {
echo (" <li>" . $row_rsMenu['menuName'] . " <img src='SiteFiles/Site/separator.jpg' /> </li>\n");
}
echo "</ul>\n";
mysql_free_result($rsMenu);
Thanks
You could also build an array and use implode when you print it out. This also separates the database model from the view a little better.
mysql_select_db($database_db_connection, $db_connection);
$query_rsMenu = "SELECT * FROM menu WHERE online = 1 ORDER BY position ASC";
$rsMenu = mysql_query($query_rsMenu, $db_connection) or die(mysql_error());
$array = array();
while($row_rsMenu = mysql_fetch_assoc($rsMenu)) {
$array[] = "<li>" . $row_rsMenu['menuName'] . "</li>\n";
}
mysql_free_result($rsMenu);
echo "<ul class='MenuBarVertical'>\n";
echo implode(' <img src="SiteFiles/Site/separator.jpg" /> ', $array);
echo "</ul>\n";
Of course the tags end up between the li instead of inside, but since you are making the li inline I think it will work.
The easy solution is to special case either the last iteration or the first one. The first one is usually easier: set $first = true outside the loop, inside the loop: if (!$first) { print 'separator'; }.
$count = 0;
$dbRows = mysql_num_rows($rsMenu);
while($row_rsMenu = mysql_fetch_assoc($rsMenu)) {
$count++;
echo (" <li><a href=\"../" . $row_rsMenu['menuURL'] . "\">" . $row_rsMenu['menuName'];
if($count < $dbRows)
echo ("</a> <img src='SiteFiles/Site/separator.jpg' /> </li>\n");
}
You could use mysql_num_rows() to get the number of rows from the result set, and build some logic against the result.
Yet another answer :
for ($i = 1; $i <= mysql_num_rows($rsMenu); $i++) {
$row_rsMenu = mysql_fetch_assoc($rsMenu);
// do something;
if ($i == mysql_num_rows($rsMenu) - 1) {
// this is the last element, do something;
}
}

Problems using GROUP BY in MySQL in a query that does a JOIN on two tables

I have two MySQL tables, $database1 and $database2. Both have a field in them called ID. I am passing the name of a town to the file using GET (i.e. it's in the URL of the PHP file that holds this code).
I can run this query...
$PlaceName = $_GET['townName'];
$PlaceName = mysql_real_escape_string($PlaceName);
$sql="SELECT * from $database1 LEFT JOIN $database2 on $database1.ID = $database2.ID WHERE PlaceName='$PlaceName'";
$query = mysql_query($sql);
echo '<h1>People who are searching for '.$PlaceName.':</h1>';
echo '<ul>';
while ($row = mysql_fetch_array($query)) {
echo "<li>ID #",$row['ID'],": ",$row['MemberPersonalName']," ",$row['MemberSurname']," -- searching for ",$row['SurnameBeingSearched'],"</li>";
}
echo '</ul>';
...and it works and all is well. Right now the output looks like this...
People who are searching for Hogwarts:
ID #137: Hermione Granger -- searching for Stern
ID #137: Hermione Granger -- searching for Engelberg
ID #503: Harry Potter -- searching for Kreindler
ID #549: Ron Weasley -- searching for Kreindler
ID #1062: Draco Malfoy -- searching for Engelberg
ID #1155: Ginny Weasley -- searching for Kreindler
ID #1155: Ginny Weasley -- searching for Streisand
But the output needs tweaking, and I'm having trouble writing my SQL query statement to reflect the changes. What I really want is for the output to look like this...
People who are searching for Hogwarts:
Engelberg is being searched by Hermione Granger (id #137) and Draco Malfoy (id #1062)
Kreindler is being searched by Harry Potter (id #503), Ron Weasley (id #549), and Ginny Weasley (id #1155)
Stern is being searched by Hermione Granger (id #137)
Streisand is being searched by Ginny Weasley (id #1155)
In other words, I need to group the output together by the field 'SurnameBeingSearched', I need to list the names of the people doing the searching in an "X, Y, and Z" output format (where it knows where to add a comma, if necessary, depending on the number of results), and I need to order the results by the 'SurnameBeingSearched' field.
Help? Thanks!
You need to list the names so this isn't an aggregation (in the SQL sense) problem. Keep your current query. You're going to have to do the grouping in code.
So something like:
$rows = array();
$last = '';
while ($row = mysql_fetch_array($query)) {
$surname = $row['SurnameBeingSearched'];
$id = $row['ID'];
$name = $row['MemberPersonalName'];
if ($last != $surname) {
$last = $surname;
$rows[] = array();
}
$rows[count($rows)-1][$id] = $name;
}
foreach ($rows as $row) {
// now display each group of names
}
You might also be able to use the MySQL GROUP_CONCAT() function.
It would look something like this...
SELECT places_tbl.name, GROUP_CONCAT(people_tbl.name)
FROM places_tbl
LEFT JOIN people_tbl ON (places_tbl.id = people_tbl.id)
GROUP BY places_tbl.id
GROUP_CONCAT() by default returns the values as comma delimited. You can probably split them up to get the formatting as you need it or use the SEPARATOR keyword. GROUP_CONCAT(fieldname SEPARATOR '-')
$PlaceName = $_GET['townName'];
$PlaceName = mysql_real_escape_string($PlaceName);
// note - added order to the query
$sql="SELECT * from $database1 LEFT JOIN $database2 on $database1.ID = $database2.ID WHERE PlaceName='$PlaceName'
ORDER BY SurnameBeingSearched, MemberSurname, MemberPersonalName";
$query = mysql_query($sql);
echo '<h1>People who are searching for '.$PlaceName.':</h1>';
echo '<ul>';
$cntr = mysql_num_rows($query);
if ($cntr > 0) {
$i = 0;
$srchd = mysql_result($query, $i, 'SurnameBeingSearched');
$mbr = mysql_result($query, $i, 'MemberPersonalName');
$mbr = $mbr . " " . mysql_result($query, $i, 'MemberSurname');
$mbr = $mbr . " (id #" . mysql_result($query, $i, 'ID') . ")";
$lin = $srchd . " is being searched by " . $mbr;
$prev = $srchd;
if ($cntr == 1) {
echo "<li>" . $lin . "</li>";
} else {
for ($i = 1; $i< $cntr; $i++) {
$srchd = mysql_result($query, $i, 'SurnameBeingSearched');
$mbr = mysql_result($query, $i, 'MemberPersonalName');
$mbr = $mbr . " " . mysql_result($query, $i, 'MemberSurname');
$mbr = $mbr . " (id #" . mysql_result($query, $i, 'ID') . ")";
if ($srchd == $prev) { // common search
$j = $i + 1;
if ($j < $cntr) { // still have data
$nxt = mysql_result($query, $j, 'SurnameBeingSearched');
if ($prev == $nxt) { // another one coming -- use the comma
$lin = $lin . ", " . $mbr;
} else {
$lin = $lin . ", and " . $mbr; // last member add the 'and' - line is done
echo "<li>" . $lin . "</li>";
}
$prev = $srchd;
} else { // ran out of data - need to finish the line
$lin = $lin . ", and " . $mbr; // last member add the 'and' - line is done
echo "<li>" . $lin . "</li>";
} else { // new search - need to print this line and start a new one
echo "<li>" . $lin . "</li>";
$lin = $srchd . " is being searched by " . $mbr;
$prev = $srchd;
} // test searched = previous
} // next i
} // only one row
} // cntr > 0
echo '</ul>';
/* note: this is not tested
I would recommend using table1 and table2 instead of database1 and database2
or better give the tables meaningful names
I would use active voice instead of passive voice
*/

PHP while loop find last row

$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
<p>$i. <?php echo $row['comment'] ?></p>
<div class="border"></div>
$i++;
}
How could I do to not output <div class="border"></div> under the last comment?
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$number = mysql_num_rows($sql);
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
echo '<p>' . $i . $row['comment'] . '</p>';
if ($i < $number)
{
echo '<div class="border"></div>';
}
$i ++;
}
Using WebDevHobo's suggestion.
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$output = array ();
while ($row = mysql_fetch_assoc($sql)) {
$output[] = $row['comment'];
}
echo join('<div class="border"></div>', $output);
$number = mysql_num_rows($sql);
This will tell you how many rows will be returned. Based on that, you can make sure that the last on does not have the DIV.
$sql = mysql_query("SELECT * FROM comments WHERE user = 1");
$i = 1;
while ($row = mysql_fetch_assoc($sql)) {
$out_data[] = "<p>$i {$row['comment']} </p>";
$i++;
}
$divider = '<div class="border"></div>';
$output = implode ($divider, $out_data);
echo $output;
$rslt = mysql_query("SELECT * FROM comments WHERE user = 1");
$i = 1;
if ($row = mysql_fetch_assoc($rslt)) {
echo '<p>'. $i . ' '. $row['comment'] . '</p>';
$i++;
while ($row = mysql_fetch_assoc($rslt)){
echo '<div class="border"></div>';
echo '<p>'. $i . ' ' . $row['comment'] . '</p>';
$i++;
} // end while
} // end if
Avoids needing to know the number of rows.
Executes the if statement only once instead of each loop.
The HTML and php were kind of messy and inconsistent, so I just assumed the whole block was within php tags. Obviously, open and close the php tag as you see fit.
This is largely a style issue, but I decided that the variable name $sql was a bit misleading, as it is often and commonly used to hold the string of the sql statement to be executed, I therefore changed the variable name to $rslt.
A general answer to this type of problem, and using Javascript because it's easy to throw in a console and play with:
var count = 0;
var foo = 3;
while( count < 3 ) {
console.log("Header - " + count);
console.log("Body - "+ count);
console.log("Footer - " + count);
count++;
}
This will print:
Header - 0
Body - 0
Footer - 0
Header - 1
Body - 1
Footer - 1
Header - 2
Body - 2
Footer - 2
The case being requested is basically saying "Print a footer on all but the last element."
If you consider the second loop iteration as simply a continuation of the first you can see how to do this without needing to find the total number of records - e.g. no need to do a second query for count. More succinctly: when you're stuck trying to figure out how to do something using a loop (or recursion) you should try actually writing out what your loop does, but without actually looping - e.g. copy and paste the loop block at least three times.
Rather than do that here, I'm just going to finish with the answer, and leave the derivation to the reader :~)
var count = 0;
var foo = 3;
while( count < 3 ) {
if( count > 0 ) {
console.log("Footer - " + (count - 1));
}
console.log("Header - " + count);
console.log("Body - "+ count);
count++;
}

Categories