This is similar to one of my previous questions here, although this is looking for a solution rather than tools to debug it. I'm trying to build a script to (amongst other things) automatically replace names entered in a MySQL database with the name bolded in WikiMedia format, so when I enter NAME: I expect to get '''NAME''':. What I actually get is NAME'''''':. I've tried a sugestion posted on the aforementioned question to remove Carriage Returns from my array using str_replace(array("\r", "\n"), array('', ''), $row); but it had no effect.
The code I'm using to generate this is:
<?php
$link = mysql_connect($host, $username, $pass);
$db = mysql_select_db($database, $link);
$query = "SELECT name FROM " . $prefix . "";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$name[] = $row['name'];
}
$sim = $_POST['sim']; //Fetches SIM from text box.
$sim_wrap = wordwrap($sim, 80, "\n"); //Constrains to 80 columns for readability.
$sim_penultimate = str_replace("::", "<nowiki>::</nowiki>", $sim_wrap);
$sim_final = str_replace($row . ":", "'''" . $row . "''':", $sim_penultimate); //Bold names
echo stripslashes($sim_final); //Removes slashes wordwrap() adds on some configurations example (James\'s).
?>
Thank you for any help you can give me, this really has me stumped.
$row is a result from mysql_fetch_array() - in other words, it's an array. Why are you concatenating it with a string ($row . ":")? Concatenating an array with a string doesn't work - you instead need to concatenate individual elements.
It seems like what you really want to do is something like this...
$names = array();
$replaces = array();
while($row = mysql_fetch_array($result)){
$names[] = $row['name'] . ":";
$replaces[] = "'''" . $row['name'] . "''':";
}
and then later on...
$sim_final = str_replace($names, $replaces, $sim_penultimate); // Bold names
Related
hope you can help, tearing my hair out here!
I have...
$result = mysqli_query($con,'SELECT this FROM that');
while($row = mysqli_fetch_array($result))
{
echo $row['this'] . ',';
}
Which returns...
222,225,243,256,260,269,273,280,295,296,
I need to remove the last comma to give me just...
222,225,243,256,260,269,273,280,295,296
I've tried trim rtrim substr and everything else I could find but none of them work. Think it's to do with the concatenation of the $row['this'] . ',' but I cant figure out how to resolve it!
Any help would be appreciated.
Cheers,
Mark.
Just let MySQL do the work for you:
$result = mysqli_query($con, 'SELECT GROUP_CONCAT(this, ',') as thises FROM that');
This constructs the results as a comma-delimited string. You can refer to it by its name, thises.
Use rtrim to remove last comma.
rtrim($my_string,',');
you can use implode
while($row = mysqli_fetch_array($result))
{
$a[]= $row['this'];
}
$b = implode(',',$a);
print_r($b);
function for implode
function imp($c){
$d= implode(',',$c);
return $d;
}
$b = imp($a);
print_r($b);
You can use substr()
This is your code
$result = mysqli_query($con,'SELECT this FROM that');
while($row = mysqli_fetch_array($result))
{
echo $row['this'] . ',';
}
Code Should like this
$result = mysqli_query($con,'SELECT this FROM that');
$my_string = "";
while($row = mysqli_fetch_array($result))
{
$my_string .= $row['this'] . ',';
}
$my_final_string = substr($my_string, 0, strlen($my_string)-1);
echo $my_final_string;
Explanation
substr(string,start,length)
string = Your generated string
start = From which position you want to start the string.
length = A positive number - The length to be returned from the start parameter. Negative number - The length to be returned from the end of the string
ORIGINAL CODE
$sentance="are you hungry too?";
function newLanguage($text) {
$sql = "SELECT in,out FROM words";
$res = mysql_query($sql) or die();
$in_array = array();
$out_array = array();
while ($row = mysql_fetch_array($res)){
$in_array[] = $row['in']; // table in, NEW words
$out_array[] = $row['out']; //table out, ENG words
}
return preg_replace($in_array,$out_array,$text);
}
$newwords = newLanguage($sentance);
echo $newwords;
AMENDED CODE:
ini_set("display_errors", "1");
error_reporting(E_ALL);
function newLanguage($text) {
$sql = "SELECT in,out FROM words";
$res = mysql_query($sql) or die();
$in_array = array();
$out_array = array();
while ($row = mysql_fetch_array($res)){
$in_array[] = '/\b' . preg_quote($row['in']) . '\b/'; // table in, NEW words
$out_array[] = $row['out']; //table out, ENG words
}
/* VERSION 2 - STATIC, FOR DEBUGGING
$in_array = array('~\you~s','~\to~s','~\too~s');
$out_array = array('noa','nie','niee');*/
return preg_replace($in_array,$out_array,$text);
}
$sentance="are you hungry too?";
$newwords = newLanguage($sentance);
var_dump($in_array);
echo $sentance;
CURRENT CODE
ini_set("display_errors", "1");
error_reporting(E_ALL);
$sentance="are you hungry too?";
function newLanguage($text) {
$sql = "SELECT * FROM words";
$res = mysql_query($sql) or die();
while ($row = mysql_fetch_array($res)){
$in_array[] = '/\b' . preg_quote($row['in']) . '\b/'; // table in, NEW words
$out_array[] = $row['out']; //table out, ENG words
}
return preg_replace($in_array,$out_array,$text);
}
$newwords = newLanguage($sentance);
var_dump($in_array);
echo $newwords;
I'm having Problems with my code, for the life of me I cannot get it to work, I have worked with preg_replace before in using a word filter. Though creating a dynamic array using query results totally throws me off. I have looked at a few tutorials but none have really helped me understand where I am going wrong.
Any help would be grateful :)
GOAL:
Creating a New Language translation. Database holds a row with 'in' & 'out' which is both the new language and local language.
PROBLEM:
I'm unsure if my Arrays are being successfully populated since my preg_replace isn't working.
----UPDATE----
Here is what my database looks like;
id in out
1 you noa
2 to nie
3 too niee
They are stored as VARCHARS
Try this:
while ($row = mysql_fetch_array($res)){
$in_array[] = '/\b' . preg_quote($row['in']) . '\b/'; // table in, NEW words
$out_array[] = $row['out']; //table out, ENG words
}
This turns the in worods into regular expressions, adding \b to match word boundaries.
My whole test code is:
<?php
$sentance="are you hungry too?";
function newLanguage($text) {
$in_array = array();
$out_array = array();
$rows = array(array('in' => 'you', 'out' => 'noa'),
array('in' => 'to', 'out' => 'nie'),
array('in' => 'too', 'out' => 'niee'));
foreach ($rows as $row) {
$in_array[] = '/\b' . preg_quote($row['in']) . '\b/'; // table in, NEW words
$out_array[] = $row['out']; //table out, ENG words
}
return preg_replace($in_array,$out_array,$text);
}
$newwords = newLanguage($sentance);
echo $newwords;
The $rows array replaces the database query, but the rest is essentially the same.
BIG thank you to Barmar for his dedicated help and patience in helping me solve my question!
I have made his answer correct since he helped me so much but if you wish to use my final code that is commented please feel free.
My Goal was to IMPORT database rows and insert them into an Array which will be used with preg_replace.
My Final Code was:
//this is the base text that will be modified using database information
$sentance="are you hungry too?";
function newLanguage($text) {
$sql = "SELECT * FROM words";
$res = mysql_query($sql) or die();
$in_array = array();
$out_array = array();
while ($row = mysql_fetch_array($res)){
// inserts the column row 'in' into an array called in_array
$in_array[] = '/\b' . preg_quote($row['in']) . '\b/';
// inserts the column row 'out' into an array called out_array
$out_array[] = $row['out'];
}
//replaced any matching words from 'sentance' with 'in_array' and replaces with 'out_array'
return preg_replace($in_array,$out_array,$text);
}
//this makes a new variable and used a function to replace the text with matches in the variable
$newwords = newLanguage($sentance);
echo $newwords;
I have tried a tons of variations, but I can't find the solution. Previously the output was like this:
word a
word b
word c
etc
I have changed some parts of code and now output is:
word a | word b | word c |
How to remove last separator?
The code is:
<div id="right">
<div id="synonyms">
<?
$separator = '<span class="pipe">|</span>';
$sql = mysql_query("SELECT DISTINCT word, id_word FROM words WHERE word LIKE '$word' ORDER BY word ASC LIMIT 100");
echo mysql_error();
while ($row=mysql_fetch_row($sql))
{
$word_synonym = $row[0];
$id_word_synonym = $row[1];
$sql2 = mysql_query("SELECT DISTINCT synonym, id_synonym FROM synonyms WHERE id_word = '$id_word_synonym' ORDER BY synonym ASC");
echo mysql_error();
$num_results =mysql_num_rows($sql2);
while ($row=mysql_fetch_row($sql2))
{
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo "".$separator."".$synonym." ";
}
}
?>
</div>
I tried to add $separator = substr($separator, -1, 0); and a lot of other suggestions, but without result.
My preference when doing something like this is to build an array of the strings, then use implode when outputting the final string. This is particularly useful because then I can do other things like merge groups, filter them, etc.
This was posted before and removed, but I think it's worth including as an optional method. Although I prefer Kolink's method, I've used this, too:
Use an iterator ($i) to identify the first (or last) item.
$i=0;
while ($row = mysql_fetch_row($sql2)) {
$i++;
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
echo ($i>1?$separator:"").'$synonym';
}
Not part of this answer, but here's an example of Kolink's (arguably superior) method:
$links=array();
while ($row = mysql_fetch_row($sql2)) {
$synonym = $row[0];
$id_synonym = $row[1];
$synonym2 = str_replace(" ", "+", $synonym);
$links[]='$synonym';
}
if (!empty($links)) {
echo implode($separator,$links);
}
I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.
I am stuck working on a problem, and would appreciate some guidance. I am working with an old system that was coded awfully, and didnt do any validating, or sanitzing of user input, so the database I'm working with is a bit missy.
I have issues with one column called "tags", used for tags for articles. But each row appears like this, and varies between them:
tag tag1 tag2 tag3
OR
tag1, tag2, tag
But I need to combine them and put them into an array that lists them by how many times each one occurs, like this:
tag(2)
tag1(2)
tag2(2)
tag3(1)
Because I'm not the most astute with php, Im not sure if I am going about the problem correctly?
Im new to manipulating arrays on this scale which is why I am stuck at this point. You can view the example below of what I am doing below:
$sql = "SELECT tags, approved FROM articles WHERE approved = '1' ";
$result = mysql_query($sql);
while( $rows = mysql_fetch_array($result) ) {
$arr = $rows['tags'];
$arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space.
$arr = str_replace(" ", " ", $arr);
// Don't know what to do next, or if this is even the right way to do it.
}
Any help is appreciated.
Thanks, Lea
Maybe this will be helpful. Modified your code to have a $tagArr for each query. If you need an overall array of tags it would be a bit different, but could easily be coded using the following.
while( $rows = mysql_fetch_array($result) ) {
$arr = $rows['tags'];
$arr = str_replace(", ", " ", $arr); // attempting to clean up the data, so that each word appends with a space.
// Don't know what to do next, or if this is even the right way to do it.
$tagArr = array();
$current_tags = explode(" ", $arr);
foreach($current_tags as $tag) {
if(!array_key_exists($tag, $tagArr)) {
$tagArr[$tag] = 1;
} else {
$tagArr[$tag] = $tagArr[$tag]++;
}
}
// now $tagArr has the tag name as it's key, and the number of occurrences as it's value
foreach($tagArr as $tag => $occurrences) {
echo $tag . '(' . $occurrences . ')<br />';
}
}