I created a PHP page that show names from a table, there is some names is too long, I want to make if $name is 12 characters then replace what after 12 characters with ...
this is my code
$query= mysql_query("SELECT * FROM `table`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$name= $arr['name'];
echo '</br>';
echo $name;
}
How can I do it?
Try:
$name = (strlen($arr['name']) > 12) ? substr($arr['name'],0,12) . "..." : $arr['name'];
This is a conditional assignment. If $arr['name'] is greater than 12 characters, then it truncates it to 12 characters and adds "...". Otherwise, it uses the full name.
if (strlen($name) > 12)
$name = substr($name, 0, 12) . '...';
https://php.net/strlen
https://php.net/substr
You can do something like this:
if( strlen($arr['name']) > 12)
{
substr($arr['name'],0,12)."...";
}
So, your code will look like:
$query= mysql_query("SELECT * FROM `table`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$name= $arr['name'];
echo '</br>';
if(strlen($name) > 12)
{
substr($name,0,12) . "...";
}
}
You can do it like this:-
<?php
$mystring = "this is a test string to check that";
if( strlen($mystring) >= 12)
{
$result= substr($mystring,0,12);
$result .='...';
}
echo $result;
?>
Related
It is a tracking system like DHL. Tracking shipment number from MySQL database using php form.
but I need it Search multiple row separate by comma from mysql using php.
<?php
$ship=$_POST['Consignment'];
$cons = explode(',',$ship);
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no = '$cons[]'";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Shipment Name: <?php echo $ship_name; ?>
Shipment Phone: <?php echo $phone; ?>
<?php }//while
}//if
else {
echo 'In else....';
?>
Consignment Number not found.Search Again.
<?php
}//else
?>
So I need my search will work with separating by comma(,).
Thanks for helping me.
You can use IN operator in that case.
<?php
$ship=$_POST['Consignment'];
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Hope it will help to you.
change your sql query you have written '$cons[]' in select query which is wrong . after explode you will get data as 1,2,3 so you just need to write variable in query not array and user IN Operator like this.
`$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";`
You should always prepare/sanitize the POST data before using it in MySql query (in terms of security):
<?php
if (isset[$_POST['Consignment']] && !empty($_POST['Consignment'])) {
$ship = $_POST['Consignment'];
$cons = explode(',', $ship);
$cons = array_filter($cons, function($v){
return trim(strip_tags($v));
});
$cons = '"' . implode('","', $cons) . '"';
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN ($cons)";
$result = dbQuery($sql);
$no = dbNumRows($result);
if ($no == 1) {
while ($data = dbFetchAssoc($result)) {
extract($data);
....
}
....
}
?>
Please Use Find IN SET
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'1,2,3,4,5')
Updated
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'$ship')
Note :- $ship Comma Separated Value not an array
I found the Answer:
if(isset($_POST['Consignment'])){
$ship=$_POST['Consignment'];
$shipment= explode(',',$_POST['Consignment']);
$ship = implode("', '",$shipment) ;
$query = "SELECT * FROM `tbl_courier` WHERE `cons_no` IN('$ship')";
$results = $mysqli->query($query);
if($results){
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["cons_no"].'</td>';
print '<td>'.$row["customerName"].'</td>';
print '<td>'.$row["customerPhone"].'</td>';
print '</tr>';
}
print '</table>';
// Frees the memory associated with a result
$results->free();
}
else {
echo "Query Not Match";
}
$mysqli->close();
}
Thanks to Answer.
<?php
include ("db.php");
$id2 = "SELECT MAX(id) FROM osalejad;";
$id = $conn->query($id2);
if (id<= 8){
while($id<= 7) {
$min = 1;
$max = 20;
$suvanumber = rand($min, $max);
$bar = (string) $suvanumber;
$prii= "vaba2" . $bar;
$sql="INSERT INTO osalejad (name) VALUES ('$prii')";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
else {
echo '8 osalejat on juba kirjas';
}
?>
I have a question, i want to insert data into MYSQl table, word with a random number, but problem is, it never work as it should - if i have 3 records in name column, then till, it adds 8 more records, instead of 5 records. Is something outside of scope atm?
I will use the DB in this code.
<?php
include("db.php");
$sql = "SELECT * FROM `osalejad`;";
$result = $conn->query($sql);
$var = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = mysqli_fetch_array($result)) {
$var[] = $row["name"];
}
} else {
/// echo "0 results";
}
//shuffle the array, and encode into json.
shuffle($var);
$brack=json_encode($var);
$testbrack= json_encode(array_chunk($var,2));
$final = '{';
$final .= '"teams":';
$final .= $testbrack;
$final .= ',"results":[[[[0,0],[null,null]],[[null,null],[null,null]]]]}';
//updating last tournament bracket.
$sql1 = "UPDATE lan_brackets SET json='$final' ORDER BY tid DESC LIMIT 1;";
$roundOne=$conn->query($sql1);
?>
This is my page code:
<?php
$dbhost="****";
$dbname = '****';
$dbusername="********";
$dbpass="*****;
$con = mysql_connect("$dbhost","$dbusername","$dbpass");
mysql_select_db($dbname,$con);
?>
<main>
<table width='100%' align='center'>
<tr align='center'>
<?php
$sql = "SELECT * FROM file ORDER BY data";
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$j = $num - 1;
$fyear = mysql_result($result, $j, "data");
$year = 2005;
while ($year <= $fyear)
{
$sql = "SELECT * FROM file WHERE posizione = 'uila/blindi.php' AND YEAR(data) = ".$year." ORDER BY data";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$num = mysql_num_rows($result);
$i = 0;
echo "<td>";
while ($i < $num)
{
$file = mysql_result($result, $i, "pdf");
$name = mysql_result($result, $i, "nome");
$type = mysql_result($result, $i, "type");
$path = mysql_result($result, $i, "posizione");
echo ""?><?php echo $name; ?><br>
<?php
$i++;
}
echo "</td>";
$year++;
}
?>
</tr>
</table>
And this is the page's error:
Warning: mysql_result() [function.mysql-result]: Unable to jump to row -1 on MySQL result index 2 in D:\Inetpub\webs\uilanotiziecom\bindi.php on line 47
The 47th line is : $j = $num - 1;
How can I fix it?
have you tried this? :
if ( $num >= 1 ) {
$j = $num - 1;
}
if your query returns 0 rows you get the error, what you do in that case is up to you
I think the below sql query is returning empty result that is where you are facing the issue.
$sql = "SELECT * FROM file ORDER BY data";
That's why $j value is -1
And FYI,
Please use proper naming conventions and unique variable names as you have used $sql for both the queries
i am retrieving results from MySQL with PHP based on user search
i want to add a automatically after every 2 s in the result
<?php
include_once("config.php");
isset( $_REQUEST['name'] ) ? $name=$_REQUEST['name'] : $name='';
$name = mysql_real_escape_string( $name );
if (strlen($name) >= 4) {
$sql = "select * from places where speciality like '%$name%'";
$rs = mysql_query( $sql ) or die('Database Error: ' . mysql_error
$num = mysql_num_rows( $rs );
if($num >= 1 ){
echo "<table id='result-table'><tr>";
while($row = mysql_fetch_array( $rs )){
echo "<td>row[cname]</td>"; //here i want to add </tr><tr> after 2 <td>s
}
}else{
echo "no records found</table>";
}
}
?>
Used $i = 1; if ($i % 2 == 0) and $i++;
<?php
include_once ("config.php");
isset ($_REQUEST['name']) ? $name = $_REQUEST['name'] : $name = '';
$name = mysql_real_escape_string($name);
if (strlen($name) >= 4) {
$sql = "select * from places where speciality like '%$name%'";
$rs = mysql_query($sql) or die('Database Error: '.mysql_error $num = mysql_num_rows($rs);
if ($num >= 1) {
$i = 1;
echo "<table id='result-table'><tr>";
while ($row = mysql_fetch_array($rs)) {
echo "<td>row[cname]</td>"; //here i want to add </tr><tr> after 2 <td>s
if ($i % 2 == 0)
echo "</tr><tr>";
$i++;
}
}
else {
echo "no records found</table>";
}
}
?>
echo "<table id='result-table'><tr>";
$currentCount = -1;
while($row = mysql_fetch_array($rs))
{
echo "<td>row[cname]</td>";
$currentCount = ($currentCount + 1) % 2;
if($currentCount == 1)
{
echo '</tr><tr>';
}
}
I suggest not putting them into a table at all; instead simply put them into <div> elements, with float:left and width:50% styles.
If you must put them into a table, and you want to do it the way you asked, you can use PHP's modulo operator (%) to divide the current record number by 2 and get the remainder. If it's 1, then add the <tr> tag:
if(++$rowNum % 2) {print "</tr><tr>";}
I am trying to make it to if I have at least 1 team created for one person, it will display the team. If they don't have a team, it will say no teams. It works if the person has at least 1 team, but nothing shows if the person is not on a team. How do I fix this?
<?php
$sql = mysql_query("SELECT * FROM teams WHERE players LIKE '%$sessiongamt%'") or die("Could not allocate information!");
$num = 0;
while($row = mysql_fetch_assoc($sql)){
$num = ++$num;
$amount1 = mysql_num_rows($sql);
$name = $row["name"];
$teamrank = $row["rank"];
$teamlink = $row["link"];
$players = $row["players"];
$teamid = $row['id'];
if($amount1 < 1){
$teams = "No Teams";
echo "$amount";
}else{
$teams = "$name";
echo "<a href='$teamlink?id=$teamid'>$teams</a>";
}
}print "$amount1";
?>
Look at the third line of this code - put it in your code on the same place instead of your line.
if($amount1 < 1){
$teams = "No Teams";
echo $teams;
}else{
$teams = "$name";
echo "<a href='$teamlink?id=$teamid'>$teams</a>";
}
Put the counting outside the while... loop
$sql = mysql_query("SELECT * FROM teams WHERE players LIKE '%$sessiongamt%'") or die("Could not allocate information!");
$amount1 = mysql_num_rows($sql); //<---- this should fix it
$num = 0;
while($row = mysql_fetch_assoc($sql)){
$num = ++$num;
$name = $row["name"];
$teamrank = $row["rank"];
$teamlink = $row["link"];
$players = $row["players"];
$teamid = $row['id'];
$teams = "$name";
echo "<a href='$teamlink?id=$teamid'>$teams</a>";
}
if($amount1 < 1){
$teams = "No Teams";
}
print "$amount1";
?>