Set max length of table cell? - php

I'm trying to figure out a way to limit the amount of information pulled from a database, that is displayed within a table as like an overview type function.
Let's say the information pulled from the database has 1000 words, but I only want the table to display 150 characters and then display "..." to indicated there is more information.
Is this possible? Like a maxlength or overflow property?
Thanks.

You could use substr() to limit the length of returned items.
$result = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_array($result)) {
// returns the first 150 characters followed by "..."
$strIn = $row['database_column'];
$strOut = substr($strIn, 150) . '...';
echo('<p>'.$strOut.'</p>');
}
If you want to check to make sure it splits properly between words, you'll want to do some further string manipulation.

Related

PHP / Mysql increment by one from previous row

I am looking to take the ID that auto increments already from the latest row in a table and increment it by one and append it on to a returned result from that same table. So if the row id is 5 and the tabledata result is product5, I need it changed to product6 in the php result. So when the data is resubmitted it is in-line with the new row ID.
EDIT:
I need it displayed and incremented before the sql insert because it's also emailed on data submit for ordering. The database insert is just to retain the order record.
Current code display results:
$conn=mysql_connect(" "," "," ");
mysql_select_db("database",$conn);
$sql="SELECT * FROM table WHERE ID=(SELECT max(ID) FROM table)";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Data: '.$result["tabledata"].'</td>
</tr>
</table>';
?>
What if you modify the query to select value after incrementing it. i.e.
SELECT ID+1 AS ID, /*all other fields of the table */ FROM table WHERE ID=(SELECT max(ID) FROM table)
So if I understand, you have two fields, not one:
id tabledata
1 PO-01
5 product5
is a Purchase order field so it stays in line with the previous just one number different (Example PO-01 to PO-02)
First thing that comes to mind is not to write that number in two places anyway. You could have
id tabledata
1 PO-%02d
5 product%d
and then wherever you had the row data, you could use
sprintf($row['tabledata'], $row['id'])
to get the "human readable" version of tabledata. Then to get the "next" ID you could just do
sprintf($row['tabledata'], $row['id'] + 1)
Otherwise, you need to extract the number from the text field. This requires that you know in advance its format (e.g. is it %d or %02d or...?).
If you know it is just the number, with variable length, as in your first example (product5 to product6), you do
$table['tabledata'] = preg_replace('#\\d+$#', $table['id'] + 1);
The above will replace the last sequence of numeric digits (here, 5; it could be 1701 for example) with 6. Or you can capture the number with preg_match and much the same expression, only in parentheses, increment it, and store it back.
If it is a fixed-length sequence of numbers as in your second example (PO-01 to PO-02), you just use substr:
$size = 2; // Two-digit number
$num = substr($table['tabledata'], -$size);
$prd = substr($table['tabledata'], 0, -$size);
$table['tabledata'] = $prd . sprintf("%0{$size}d", $num + 1);
An even more complicated solution would be to merge the two versions into a "decoding" function that would count leading zeroes and digit lengths and use this to determine the format being used. This however would have problems in some cases (e.g. maybe the next number out from AB-99 is not AB-100 but AC-00 or AC-01), so all in all I think this is best left to someone with the knowledge of the specific domain.

How to select random rows from a table in MySQL

I am creating a project which involves getting some questions from mysql database. For instance, if I have 200 questions in my database, I want to randomly choose 20 questions in such a way that no one question will be repeated twice. That is, I want to be able to have an array of 20 different questions from the 200 I have every time the user tries to get the list of questions to answer. I will really appreciate your help.
SELECT * FROM questions ORDER BY RAND() LIMIT 20;
PS^ This method not possible for very big tables
Use Google to find a function to create an array with 20 unique numbers, with a minimum and a maximum. Use this array to prepare an SQL query such as:
expression IN (value1, value2, .... value_n);
More on the SQL here.
Possible array filling function here too.
Assuming you have contiguously number questions in your database, you just need a list of 20 random numbers. Also assuming you want the user to be able to take more than one test and get another 20 questions without duplicates then you could start with a randomised array of 200 numbers and select blocks of 20 sequentially from that set i.e.
$startQuestion=1;
$maxQuestion=200;
$numberlist= range(1,$maxQuestion);
shuffle($numberlist);
function getQuestionSet( $noOfQuestions )
{
global $numberlist, $maxQuestion, $startQuestion;
$start= $startQuestion;
if( ($startQuestion+$noOfQuestions) > $maxQuestion)
{
echo "shuffle...\n";
shuffle($numberlist);
$startQuestion=1;
}else
$startQuestion+= $noOfQuestions;
return array_slice($numberlist,$start,$noOfQuestions);
}
// debug...
for($i=0; $i<42; $i++)
{
$questionset= getQuestionSet( 20 );
foreach( $questionset as $num )
echo $num." ";
echo "\n";
}
then use $questionset to retrieve your questions
If you know how many rows there are in the table, you could do use LIMIT to your advantage. With limit you specify a random offset; syntax: LIMIT offset,count. Example:
<?php
$totalRows = 200; // get his value dynamically or whatever...
$limit = 2; // num of rows to select
$rand = mt_rand(0,$totalRows-$limit-1);
$query = 'SELECT * FROM `table` LIMIT '.$rand.','.$limit;
// execute query
?>
This should be safe for big tables, however it will select adjacent rows. You could then mix up the result set via array_rand or shuffle:
<?php
// ... continued
$resultSet = $pdoStm->fetchAll();
$randResultKeys = array_rand($resultSet,$limit); // using array_rand
shuffle($resultSet); // or using shuffle
?>

php - get character count between two points encased in quotes

Ok this is going to be weird but I need it
I am trying to get the character count for a huge line of code between some particular quotes ". Basically I need to be able to get everything between the 3rd quote in the beginning and the 5th quote at the end.
So here is an example
a:2:{s:10:"categories";s:5758:"...........";s:5:"posts";s:6:"a:0:{}";}
I need to know what the character count is of all the periods. There is actually code in place of those periods.
Since there are 11 periods then my character count will be 11. The only consistent thing is the quotes in this so I need to base off that.
Any help would be awesome.
Here is my code. I am basically creating the code and adding some custom labels. I tried serializing the code first before I unserialize it but that didn't seem to work.
<?
$thisisit .= 'a:2:{s:10:"categories";s:5481:"a:40:{';
include('connect.php');
$sql = "SELECT * FROM wp_terms ORDER BY term_id ASC LIMIT 40";
$result = mysql_query($sql);
$count = 0;
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
$charactercount = strlen($name);
$term_id = $row['term_id'];
$thisisit .= 'i:'.$count.';a:2:{s:11:"filter_name";s:20:"add_keyword_category";s:11:"filter_args";a:7:{s:12:"filter_value";s:'.$charactercount.':"'.strtolower($name).'";s:19:"filter_search_title";s:1:"1";s:21:"filter_search_excerpt";i:0;s:21:"filter_search_content";s:1:"1";s:21:"faf_filter_categories";a:1:{i:4;s:3:"'.$term_id.'";}s:17:"filter_match_word";i:0;s:17:"filter_match_case";i:0;}}';
//echo "<br><br>";
$count++;
}
$thisisit .= '}";s:5:"posts";s:6:"a:0:{}";}';
$array = unserialize($thisisit);
echo strlen($array['categories']);
?>
Actually this data looks serialized. The correct solution would be to use php function unserialize.
Then, given your structure, to know the length of that element:
strlen(unserialize($data)['categories']);
If you run old php, you need to store the result in a temporary variable:
$array = unserialize($data);
echo strlen($array['categories']);
If your serialized data is corrupted (as in "not received from proper execution of serialize"), as it seems from your example, we can return to your original task:
get everything between the 3rd quote in the beginning and the 5th quote at the end
The simplest way to achieve that is:
implode("'", array_slice(explode("'", $data), 3, -5));

php count returning 1 not 0 from mysql_query when empty

I am trying to get a count and I am getting 1 instead of 0 from it. I have looked thoroughly though the web and this site. I have even been trying to figure it out on my own for a long time. I keep coming empty handed here.
So Basically what I am trying to do is make a like system for my users. I can get everything to work correctly the count works except for one thing. When they have liked it it returns 1 not 0 which it should be.
Here is my code for the count. I am not posting all the coding for security reasons and it really doesn't need to since its about the counting part not the rest.
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$like1 = $row['like_array'];
$like3 = explode(",", $like1);
$likeCount = count($like3);
}
So here is the code that determines the number. Any ideas what is wrong with this? Why its returning 1 not 0 when the item is empty?
// you do escape your id right??? (sql injection prevention)
$sql_like = mysql_query("SELECT * FROM posts WHERE mem2_id='$id' ORDER BY post_date DESC LIMIT 40");
while($row = mysql_fetch_array($sql_like)){
$likeCount = 0;
$like1 = trim($row['like_array']);
if ($like1) {
$like3 = explode(",", $like1); // exploding emtpy string would result in array('')
$likeCount = count($like3);
}
}
Calling explode on an empty string gives an array containing the empty string. This is one element, not zero.
I would suggest that you change your database design if possible so that you don't store the values separated by commas. Use a separate table instead.
If you can't change the database design you can handle the empty string separately.
count() returns the number of indexes in an array or something in an object (PHP: count - Manual).
if a string var is used rather than an array or object it returns 1. it has to get a null value in order to return 0.
you can give it a go by trying:
print count("");
and
print count(null);
You'll have better luck if you use explode() to break the sql output into an array and then run a check with an if statement. Something like the following:
$like3 = explode(',',$like1);
if (count($like1)=1 && $like1[0] == '')
// etc ..
I hope this helps

read random lines from a record MySQL-PHP

i will keep it simple to understand :
1) i have a database with 2 columns - word and text
2) Each word has approx. 600,000 lines of text associated with it.
3) Iam a .net person shifting to php and mysql - so a little knowledge.
MY requirement :
1) I will pass the word through a form
2) The form will connect to the database and should display 2000 random lines from those 600,000 which should be non-repetitive
My current progress :
<?php
$con = mysql_connect("localhost","text_minx","pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Data
WHERE word='health'");
while($row = mysql_fetch_array($result))
{
echo $row['lines'];
echo "<br />";
}
?>
This shows all the lines. What i want is to read this $row['lines'] in a possible array and randomly select 2000 lines from it - and they should be non-repetitive.
Any help please?
Something like this:
$result = mysql_query("SELECT DISTINCT * FROM Data WHERE word='health' ORDER BY RAND() LIMIT 2000");
It's more efficient to select the 2000 random lines by MySQL instead of by PHP, as above.
Also note that SELECT DISTINCT will select only unique rows, which you should probably remove anyway. If you specify the column names instead of using * then you can choose which columns you want to be unique - although this also depends somewhat on how your table is built.
i think this is the way you want
SELECT * FROM Data
WHERE word='health' ORDER BY RAND() LIMIT 0,2000
this will give you 2000 records sorted by any random order
You need to split your row result into array (as it's currently a string), and then you can select 2000 lines randomly.
Assuming that the text has like breaks as line separators, it would look like that:
echo $row['lines']; //starts from this line of your code
$data = explode("\n", $row['lines']);
shuffle($data);
$random_lines = array_slice($data, 0, 2000);
This does not take care of non-repetition, though. If I understand your need correctly, you can use array_unique() function before passing it to shuffle().

Categories