PHP combine values from loop - php

If I want to display the text as follows in example, how can it be done?
$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp)) {
$tekst2=$p['friend'].", ";
}
$text_complete=$tekst1.$tekst2;
echo $text_complete;
$text_complete should look like: "Your total number of friends are: 3. Your friends are: John, Mike, Michael". But, using this code above I get "Your total number of friends are: 3. Your friends are: John,"
How can I combine both texts, the one obtained from the loop and the one which is fixed?

I think you shoul do like this:
$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
$friends = array();
while($p = mysql_fetch_array($tmp)) {
$friends[] = $p['friend'];
}
$tekst2= implode(', ', $friends);
$text_complete=$tekst1.$tekst2;
echo $text_complete;
otherwise you overwrite the variable each time!
EDIT - i corrected the code to use implode as in Xaerxess answer. Previousli i just concatenated and use a substr to remove trailing comma and space

You can use:
$tekst2 .= $p['friend'].", ";
To add to the variable (rather than overwriting it. Then remove the trailing comma:
$text_complete=$tekst1. rtrim( $tekst2, "," );

$tekst2 = new Array();
while($p=mysql_fetch_array($tmp)) {
$tekst2[] = $p['friend'];
}
$text_complete = $tekst1 . implode(', ',$tekst2);
But better would be to use GROUP_CONCAT in sql

$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst = '';
$tekst='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp)) {
$tekst.=$p['friend'].", ";
}
echo $tekst;

$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp))
{
$tekst1 .= $p['friend'].", "; // add friend names from MySQL result.
}
$tekst1 = substr($tekst2, 0, -2);//Remove comma.
echo $tekst1; // Outputs the wanted string

Use PHP implode / join funciton, so there isn't any trailing comma at the end. In this case:
$fiends = array();
while($p = mysql_fetch_array($tmp)) {
$friends[] = $p['friend'];
}
implode(', ', $friends);
EDIT: I basically doubled Billy Moon answer. What's more don't use mysql_* functions - they're deprecated not recommended - see comments below.

Related

add value +1 in phrase number

I want to add value in phrase in database sql in database i save phrasr like this
DO-2500-01
DO-2500-02
now my question how can add +1 in last value like this DO-2500-03 / DO-2500-04
this my code
$getse = $DB_con->prepare("SELECT serial FROM `customer` WHERE user_add=:id ORDER BY serial DESC LIMIT 1");
$getse->execute(array(":id"=>$user_id));
$getse = $getse->fetch(PDO::FETCH_OBJ);
$addone = $getse->serial + 1;
echo $addone;
this is my code i get last serial and i want to add +1 for example last serial in database is DO-2500-04 I want to get this value and add +1 To become like this DO-2500-05
Split string, increase the last part and combine it back
$addone = explode('-', "DO-2500-04");
$addone[count($addone)-1] += 1;
// Append 0 if the last part less then 10
$addone[count($addone)-1] = str_pad($addone[count($addone)-1], 2, 0, STR_PAD_LEFT);
echo $addone = implode('-', $addone);
You can get this based on your requirement.
If DO-2500-99 should be DO-2501-00 then below code can work.
$serialArr= explode('-', $getse->serial);
$serialNo = (int)$serialArr [1].$serialArr [2];
$newSerialNo = $serialNo + 1;
$newSerialNo = substr($newSerialNo, 0, -2)."-".substr($newSerialNo , -2);
$newSerial = $serialArr[0].'-'.$newSerialNo;
If DO-2500-99 should be DO-2500-100 then below code can work.
$getse = 'DO-2500-99';
$serialArr= explode('-', $getse->serial);
$serialNo = (int)$serialArr [2];
$serialArr[2] = $serialNo + 1;
$newSerial = implode('-',$serialArr);
DO-2500-04 it's a String value and you cannot use arithmetic operators on it. If you just want last counter to get incremented, what you need to do is get the last value by splitting the string by -.
Then get the last value and increment it and then again join the array by -.
To split and join the array we can use explode() and implode().
This is how you can get the last value from string using explode()
$values=explode("-","DO-2500-04"); // $values is now array.
$lastvalue=(int)$values[2];
$lastvalue++;
if($lastvalue<9) {
$lastvalue = "0" . $lastvalue;
}
$values[2]=$lastvalue;
$incremented_string=implode("-",$values);
First parameter in explode denotes the chracter by you want to split the string same as first parameter in implode denotes the glue by you want to join the array.
http://php.net/manual/en/function.explode.php
http://php.net/manual/en/function.implode.php
Just for fun, you could do a lot of this in the SQL like:
$getse = $DB_con->prepare("SELECT serial,
LEFT(serial,8) AS serialBase,
SUBSTRING(serial,8) AS serialIdx
FROM `customer` WHERE user_add=:id
ORDER BY serial DESC LIMIT 1");
$getse->execute(array(":id"=>$user_id));
$getse = $getse->fetch(PDO::FETCH_OBJ);
$addone = $getse->serialBase + str_pad(($getse->serialIdx + 1),2,'0',STR_PAD_LEFT);
echo $addone;
Updated the SQL.

Can i select data from mysqli database using SUBSTR to refine the query

I am trying the use refine tools for a search on my website. The bit i'm stuck with is search by start letter. For example i could use a wildcard '%X%' but his would return anything that contained the letter 'x'.
I read on few sites that SUBSTRING can be used in mysql queries
http://dev.mysql.com/
http://www.kirupa.com/
https://stackoverflow.com/questions/6302027
This is what I have so far but returns nothing. There is data in the database that should return with the query.
public function refineUsersFollowers($user_id,$q){
if($this->databaseConnection()){
// get the users followers
$state = array(1,2);
$stmt = $this->db_connection->prepare("SELECT * FROM friends WHERE id_2 = :1 AND Friend_Request_State = :2 OR id_2 = :3 AND Friend_Request_State = :4");
$stmt->bindParam(':1', $user_id);
$stmt->bindParam(':2', $state[0]);
$stmt->bindParam(':3', $user_id);
$stmt->bindParam(':4', $state[1]);
$stmt->execute();
// format the SQL OR statements
$sql = '';
$ids = [];
while($rows = $stmt->fetch(\PDO::FETCH_ASSOC)){
array_push($ids,$rows['id_1']);
}
for($x = 0; $x < count($ids); $x++){
if(count($ids) == 1){
//if there is one result
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x;
}else if($x == (count($ids) - 1)){
// last entry
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x;
}else{
//continue loop
$sql.= ' user_id = :'.$x." AND SUBSTRING('first_name',0,1) = :".$x.$x." OR";
}
}
$stmt = $this->db_connection->prepare("SELECT * FROM account WHERE ".$sql);
for($x = 0; $x < count($ids); $x++){
$stmt->bindParam(':'.$x,$ids[$x]);
$insert = $x.$x.'';
$stmt->bindParam(':'.$insert,$q);
}
$stmt->execute();
$results = $stmt->fetch(\PDO::FETCH_ASSOC);
print_r($results);
// check for followers that start with letter
}
}
The first part of the function is fine, this gets an array of id's which is then placed together as an SQL string. Is the SQL not returning results because SUBSTRING is not supported in this way?
If so is there a way of producing a query like this or would it be easier to pull every result from the database then check them in a different function?
You have two issues with this expression:
SUBSTRING('first_name', 0, 1) = :".$x.$x;
First, substr() in SQL (in general) starts counting with 1 and not 0. So, the first argument should be 1.
Second, you have the first argument in single quotes. So, at best, this would return the letter 'f'. Here is a simple rule: Only use single quotes for string and date constants. Never use single quotes to refer to column names.
There are several way to write what you want. Here are three:
SUBSTRING(first_name, 1, 1) = $x
LEFT(first_name, 1) = $x
first_name like '$x%'
You query can be greatly simplified with the LIKE operator. This:
"AND SUBSTRING('first_name',0,1) = :".$x.$x;
can become this:
"AND first_name LIKE '".$x.$x."%'";
I'm not sure what the $x.$x is for, so I just left it in for illustrative purposes.

PHP - Retrieve multiple records from a single mysql table and append to a string

I have the following table in mysql. I need to select the Hid(s) from this table and append the results to a string '$s'. It would be great if you could help.
Table name : CASES
Did Hid Year Case
--- --- ---- ----
1 1 2011 6
1 1 2012 7
2 2 2011 40
2 2 2012 10
php code segment:
$did=1;
$yr=2011;
$s='';
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";
$r=mysql_query($q);
while($rw=mysql_fetch_assoc($r))
{
//I need to append the Hid(s) to a String '$s' declared above
}
Assuming your query works, which it looks like it might:
$did=1;
$yr=2011;
$s='';
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";
$r=mysql_query($q);
while($rw=mysql_fetch_assoc($r))
{
$s .= $rw['Hid'];
}
That will just give you a string with all of the Hids together.. if you want to have a character in between or something else, you could:
$did=1;
$yr=2011;
$s=array();
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";
$r=mysql_query($q);
while($rw=mysql_fetch_assoc($r))
{
$s[] = $rw['Hid'];
}
$result = implode( ',', $s );
$result above will end up with a comma-separated list of Hids.
Use the string concatenation operator:
$s .= $rw['Hid'];
Get/ retrieve the data's to an array and implode it to a string. Refer
http://php.net/manual/en/function.implode.php
for implode
$did=1;
$yr=2011;
$s='';
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";
$r=mysql_query($q);
while($rw=mysql_fetch_assoc($r))
{
$s .= $rw['hid'] . '<br />';
}
echo $s;

PHP and mysql Ignoring the special chracters present in the database

a little help on this one, here are its details
[Products]
id int
name text
category
color
Problem is the values of the color field, sample values are:
GOLDRED
GOLD-RED
GOLD/RED
BLUE/GREEN-RED
WHITE GOLD-YELLOW/ORANGE
I could very much clean the search query such as this sample using a basic function
"select * from products where color=".cleanstring($stringval)." limit 1";
function cleanstring($var) {
$newtext = $var;
$newtext = preg_replace("/[^a-zA-Z0-9\s]/", "", $newtext);
$newtext = str_replace(" ", "", $newtext);
$newtext = strtoupper($newtext);
return $newtext;
}
The problem is with the content. It's thousands of records without any form of standard in using a naming convention.
I want to select those records with its values clean similar to my cleanstring().
Example:
Query = GOLDRED
Can select
GOLD-RED
GOLD RED
GOLDRED
GOLD/RED
GOLDRED
Any solution that you could recommend? Code is in PHP/MySQL.
"select * from products where 1".cleanstring($stringval);
function cleanstring($var) {
$color_list = array('GOLD','RED','GREEN','WHITE');
$sql_where='';
foreach( $color_list AS $v){
if(strpos($var, $v)!==false){
$sql_where .=" AND color LIKE '%{$v}%'";
}
}
return $sql_where;
}
//select * from products where 1 OR color LIKE '%GOLD%' OR color LIKE '%RED%'
REMARK:
input: GOLDRED ,
match: GOLD RED,GOLD-RED,GOLD/RED..... GOLD/RED/ABC,RED_GOLDGREEN,
may be after get all data , then make func ranking by match % ,like search engine
Probably You could make just a MySQL regexp with 'GOLD.?RED' or 'GOLD(-|[[:space:]])?RED' ?
That's an online example I made : http://regexr.com?34mmg
Not the best way, and I am sure has tons of downfalls, but if I did not make any mistakes in php code (don't have machine to try it out), it would do the work:
"select * from products where color REGEXP '".cleanstring($stringval)."' limit 1";
function cleanstring($var) {
$var = preg_replace('![-\/ ]+!', '', $var);
$strLength = strlen($var);
$parts = array();
for ($i = 1; $i <= $strLength; i++) {
$parts[] = ($i > 0) ? substr($var, 0, $i).'[-/ ]?'.substr($var, $i);
}
return "[[:<:]](".implode('|', $parts).")[[:>:]]";
}
It would output something like this:
"select * from products where color REGEXP '[[:<:]](G[-/ ]?OLDRED|GO[-/ ]?LDRED|GOL[-/ ]?DRED|GOLD[-/ ]?RED|GOLDR[-/ ]?ED|GOLDRE[-/ ]?D)[[:>:]]' limit 1"
which basically breaks your keyword in pieces letter by letter, i.e.
G OLDRED
GO LDRED
GOL DRED
GOLD RED
GOLDR ED
GOLDRE D
and do the "LIKE" statement on them but with smarter word boundaries and instead of just space, it considers "-" and "/" as well.

Cannot insert sentence to database

I have some sentences. I have to choose the sentences that consist of more than 6 words. and then they will be inserted to database.
<?php
require_once 'conf/conf.php';
$text = " Poetry. Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
$sentences = explode(".", $text);
foreach ($sentences as $sentence) {
if (count(preg_split('/\s+/', $sentence)) > 6) {
$save = $sentence. ".";
$sql = mysql_query("INSERT INTO tb_name VALUES('','$save')");
}
}
?>
The result is only the second sentence that inserted in database => 'Do you read poetry while flying? Many people find it relaxing to read on long flights'. whereas the third sentence also should be inserted. please help me, thank you : )
Here is the solution you're looking for. You cannot add multiple rows since your ID value is left unspecified and it is the key into the table. Since you want to add the sentences to the same row, you need to execute one query.
$text = " Poetry. Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
$sentences = explode(".", $text); $save = array();
foreach ($sentences as $sentence) {
if (count(preg_split('/\s+/', $sentence)) > 6) {
$save[] = $sentence. ".";
}
}
if( count( $save) > 0) {
$sql = mysql_query("INSERT INTO tb_name VALUES('','" . implode( ' ', $save) . "')");
}
Now, both sentences will be inserted into the same row in the database, separated by a space. You can change what they're separated by if you modify the first parameter to implode().
The query that gets generated is this:
INSERT INTO tb_name VALUES('',' Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories.')
Replace:
$sentences = explode(".", $text);
with this:
$newSentences = array();
$sentences = preg_split("/(\.|\?|\!)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$odd = false;
foreach($sentences as $sentence) {
$sentence = trim($sentence);
if($sentence != '') {
if(!$odd) {
$newSentences[] = $sentence;
} else {
$newSentences[count($newSentences) - 1] .= $sentence;
}
$odd = !$odd;
}
}
It separates sentences ending in with . or ? or !. The foreach just reassembles the sentences.
Example here: http://codepad.org/kk3PsVGP

Categories