I'd like to convert an array to string with newline characters for simplest text formatting. The array is a result of a mysql select query and I suppose I need a loop which uses the implode function to convert to string and separate the fields with something (i.e. " * ") and at the end of each row ads a newline character.
sample output
2018-06-22 * meeting * They didn't want to buy anythin
2018-06-23 * * called and wanted to buy something
2018-06-24 * meeting * Gave specification
I was thinking something like this (but I am wrong and this is why I ask):
$Diary =''; // start with empty string
$array = mysqli_fetch_array($fetch);// fetched already
$length = count($array);
for ($x = 0; $length; $x++ + 3) {
$temparray = // use a temp array for one row only
$Diary = // increment a string until the end of the row, add newline at the end
}
And here's the answer. "Thanks" for all the downvoting.
$Diary ='';
$query = 'SELECT tb2_date, tb2_note, tb2_entry from DiaryTable WHERE tb2_tb1ID =
"'.$HiddenID.'" ORDER BY tb2_date DESC';
$resulto = mysqli_query($dbc, $query);
while ($rows = mysqli_fetch_row($resulto)) {
$rowimploded = implode(' ** ', $rows);
$newline = "\r\n";
$Diary = $Diary.$rowimploded.$newline;
}
mysqli_free_result($resulto);
// echo $Diary or whatever...
Related
The code:
<?php
$tableName = 'users';
$position = 1;
$paths = ['index'];
$sqlFormat = "SELECT * FROM %s WHERE (";
for ($i =0; $i < count($paths); $i++){
if ($i == (count($paths)-1)){
$sqlFormat .= "path LIKE '%%$paths[$i]%%') ";
}
else{
$sqlFormat .= "path LIKE '%%$paths[$i]%%' OR ";
}
}
$sqlFormat .= "AND (position = $position) AND published = 'Y' ";
$sqlFormat .= "ORDER BY weight ASC";
$sql = sprintf($sqlFormat, $tableName);
echo $sql;
Symptoms:
When the $paths array contain ordinary string it works fine. However, if we set paths to $paths = ['index%']; it generates PHP Warning: sprintf(): Too few arguments.... In other words, if $paths contains values has the % sign. In this situation I could not able to use %% to escape, like occurred in the like clause of the SQL above ...LIKE '%%$paths[$i]%%...because $paths may contain % optionally.
I could not able to find a way that let optional escaping of % if it exists. All similar questions talk about escaping of fixed values
There is a solution that I have found by using str_replace() for the elements of the array paths to replace one % by two %% to solve the issue:
$sqlFormat .= "path LIKE '%%".str_replace('%','%%',$paths[$i])."%%') ";
So if the the element contains any single % it would be escaped for the sprintf by doubling it.
I have the code from the database, the data should appear automatically in sequence. the code is composed of text and number like this CO-00001 but when I generate the code it just adds one digit in the back but not add the value of example CO-00001 to CO-000001 how to solve it?
ex :
$id = 0902340
$query = "SELECT substr(code_id,3,5) as cd FROM tb_inv WHERE substr(code_id,3,5) = '".$id."' ORDER BY code_id DESC LIMIT 1";
$get_id = $this->db->query($query);
$show_id = $get_id->num_rows();
$new_code = $get_id->row();
if($show_id > 0){
$new = $new_code->cd + 1;
$fix_code = $new;
}else{
$fix_code = 'CO-00001';
}
you can't do algebra on alphabets, therefore you need to split the alphabets and the numerics like so:
$id = 0902340
$query = "SELECT substr(code_id,3,5) as cd FROM tb_inv WHERE substr(code_id,3,5) = '".$id."' ORDER BY code_id DESC LIMIT 1";
$get_id = $this->db->query($query);
$show_id = $get_id->num_rows();
$new_code = $get_id->row();
if($show_id > 0){
$prefix = substr($new_code->cd, 0, 3); // get the prefix 3 chars at front
$number = substr($new_code->cd, 3); // get the remaining chars
$new = $number + 1; // add it with 1, php automatically convert strings that can be converted to numbers
$fix_code = $prefix . substr("00000" . $number, -5); // re-assemble the code
}else{
$fix_code = 'CO-00001';
}
you can split the id into two parts, the string one, and the digit one. then increment the digit part then re concat the two parts again
list($strPrefix, $digitPart) = split('-', $oldId);
$digitPart++;
$newCode = $strPrefix . '-' . $digitPart;
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.
I basically want to scan a load of comments for illegal words and then replace those illegal words with a clean version.
I have two arrays, one array has all the comments to check, the other array has all of the illegal words to look for.
The first for loop gets the comments, the nested for loop then scans the comments for each of the illegal words and replaces them. The thing is though - it doesn't actually seem to work. Could you please advise if it is a problem with my loop structure, or the actual update logic?
$numComments = count($commentsToCheck);
$numIllegalWords = count($illegalWords);
for($i = 0; $i <= $numComments; $i++)
{
$message = $commentsToCheck[$i]['message'];
$commentId = $commentsToCheck[$i]['id'];
//error_log($message.'-'.$commentId);
for($j = 0; $j <= $numIllegalWords; $j++)
{
//Get word to replace with
$word = $illegalWords[$j]['word'];
//error_log($word);
$length = strlen($word);
$first = substr($word,0);
$last = substr($word,-1);
$starLength = $length - 2;
$replacement = $first.str_repeat('*',$starLength).$last;
$newMessage = preg_replace('/\b'.$word.'\b/i', $replacement, $message);
//Update the comment
$sql = "UPDATE ow_base_comment SET message = $newMessage WHERE id = $commentId LIMIT 1";
OW::getDbo()->query($sql);
}
}
Shouldnt your query not be what I placed below, since it wont see now the actual variables in the query. It will technincally just update nothing, cause there is no actual variable set.
$sql = "UPDATE ow_base_comment SET message = '".$newMessage."' WHERE id = '".$commentId."' LIMIT 1";
It's a common error to forget the quotes within PHP.
I want to search in a database with variable positions. The variables are created here:
&numbers //= user input
&naar // = user input
$number = range($numbers+1, $naar -1); //define the range between the inputs
foreach ($number as $key=>$val){
$number[$key] = $letter.$val;} //define the array
$string = implode (' ',$number); // make a string from the array
This works fine. The output is a string that contains a minimum of 0 outputs and a maximun of 7 outputs. For example: A2 A3 A4 A5
I want the database to search if something is at one of the generated positions. Ive got this already:
$query="select chess_id from stelling where positie=\"".$number."\"";
$result = mysql_query($query, $connection);
$spring = 0;
if(mysql_num_rows($result)>0)
{
$spring = mysql_result($result, 0);
}
echo "$spring";
With this code only the last generated $string output will be checked. How can i let the database check all generated string code? For example:
$string = `A2 A3 A4 A5`
$query="select chess_id from stelling where positie=\"".$number."\"";
will only check A5
sample rows from table:
wt,A1
wp,A2
wl,A3
wq,A4
Well I am not shure what exactly is your problem but why don't you use IN statement ?
$string = '(`' . implode('`, `',$number) . '`)';
$query="select chess_id from stelling where positie IN {$string}";