I have programmed this function
function bad_words($val){
global $pre;
$sql = mysql_query("SELECT * FROM " . $pre . "BAD_WORDS") or die(mysql_error());
$rs = mysql_fetch_assoc($sql);
if (mysql_num_rows($sql) > 0) {
$bad_words = $rs['BAD_WORD'];
$replace = $rs['REPLACE'];
}
$val = str_ireplace($bad_words, $replace, $val);
return $val;
}
BAD_WORDS Table (ID, BAD_WORD, REPLACE)
When I use this function it replaces word with id = 1 but doesn't replace the other words.
What am I missing?
You are fetching only the first row from the table. You have to use a loop to iterate through
all the rows in the result set.
function bad_words($val)
{
global $pre;
$sql = mysql_query("SELECT * FROM " . $pre . "BAD_WORDS") or die(mysql_error());
if (mysql_num_rows($sql) > 0) {
while($rs = mysql_fetch_assoc($sql)) {
$bad_words[] = $rs['BAD_WORD'];
$replace[] = $rs['REPLACE'];
}
}
$val = str_ireplace($bad_words, $replace, $val);
return $val;
}
Well, that is because you are not looping through the resulting rows, you are only executing code on the first one. Once you determine there is one or more rows (if (mysql_num_rows($sql) > 0)), You'll need to loop through the records one at a time and perform the action.
check this for more: http://php.net/manual/en/function.mysql-fetch-array.php
Related
I want to translate each words in array:
$myarray = array("hi","bro");
So I wrote a translate function like this:
function translate($word) {
foreach ( $word as $key_translate ) {
$array = array();
$sql = mysql_query("SELECT * FROM `translate` WHERE name = '".$key_translate."' ");
if ( mysql_num_rows($sql) == 1 ) {
$row = mysql_fetch_array($sql);
$name = $row['fa_name'];
return $name;
//retuen array($name);
}
else {
return $key_translate;
//return array($key_translate);
}
}
}
And using this to show translated array:
print_r (translate($myarray));
But it's not returning array, it's just showing first key as string.
How can I return array in function?
Don't return inside the loop, that exits the whole function immediately and just returns that one element. Accumulate the results in an array, and return that.
function translate($word) {
$result = array();
foreach ( $word as $key_translate ) {
$sql = mysql_query("SELECT fa_name FROM `translate` WHERE name = '".$key_translate."' ");
if ( mysql_num_rows($sql) == 1 ) {
$row = mysql_fetch_array($sql);
$result[] = $row['fa_name'];
}
else {
$result[] = $key_translate;
}
}
return $result;
}
Also, there's no reason to use SELECT * if you're only interested in fa_name.
Try this:
function translate($word) {
foreach ($word as $key => $translate) {
$sql = mysql_query("SELECT * FROM `translate` WHERE name = '" . $translate . "' ");
if (mysql_num_rows($sql) == 1) {
$row = mysql_fetch_array($sql);
$word[$key] = $row['fa_name'];
}
}
return $word;
}
Working on a link shortening script and I'm stumped. I figured the following code would function as needed however, I get an execution time out related to $str .= $charset[mt_rand(0, $count-1)];. I have scoured over the code several times, I can't find what I am doing wrong.
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
function shrinkURL($url) {
$is_unique = false;
$num = 4;
$random_string = randString($num);
$count = 0;
while (!$is_unique) {
$q1 = "SELECT id FROM linkShortner WHERE short = '".$random_string."' LIMIT 1";
$result = mysql_query($q1) or die(mysql_error());
if ($result === false) // if you don't get a result, then you're good
$is_unique = true;
else // if you DO get a result, keep trying
$count++;
if ($count >= 10) {
$num = (strlen($random_string) + 1);
$random_string = randString($num);
$count = 0;
}
$random_string = randString($num);
}
$shortURL = "https://domain.com/l/".$random_string;
$q2 = "INSERT INTO linkShortner (id, destination, short, shorURL, creationDate) VALUES (NULL, '".$url."', '".$random_string."', '".$shortURL."', '".$DateTime."')";
$r2 = mysql_query($q2) or die(mysql_error());
return $shortURL;
}
$shortURL = shrinkURL('http://domain.com');
echo $shortURL;
Any help would be greatly appreciated, think maybe I am just burnt out.
My guess is that at some point your function randString() will be called with the $length argument being 0.
This would make:
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
get stuck, because the first iteration would be while (-1), which is true. And then while (-2), which is also true.. etc etc etc.
I would change your while ( $length-- ) to while ( $length-- >= 0 )
Changed if ($result === false) to if (!mysql_num_rows($result)) and all is well. if ($result === false) is for mysqli which is not being used here.
Basically the shrinkURL function scours the DB for a matching string before trying to insert a unique string/row, if ($result === false) would never = false because the value of $result is MySQL_query($q1) therefore producing an endless loop.
I have to store into MySQL from PHP quite a lot; usually the content to be stored I have in arrays. So I have written a small set of helper functions that saved me a lot of time.
This is the main function store that stores $array into MySQL $table:
function store($array, $table, $limit = 1000, $mode = '') {
if (empty($array)) return FALSE;
$sql_insert = "INSERT INTO `".$table."` (";
$array_keys = array_keys($array);
$keys = array_keys($array[$array_keys[0]]);
foreach ($keys as $key) $sql_insert .= "`".$key."`,";
$sql_insert = replaceEND($sql_insert, ') VALUES ', 1);
$count = 1;
$sql = $sql_insert;
foreach ($array as $array_num => $row) {
$sql .= '(';
foreach ($row as $key => $value) {
$string = $value;
if (!is_null($value)) {
$sql .= "'".str_replace("'", "\'", $string)."',";
} else {
$sql .= "NULL,";
}
}
$sql = replaceEND($sql, '),', 1);
$count = checkInsert($sql, $count, $limit);
if ($count == 0) {
if ($mode == 'PRINT') echo $sql.'<br />';
$sql = $sql_insert;
}
$count++;
}
$last = lastInsert($sql);
if ($last) {
if ($mode == 'PRINT') echo $sql.'<br />';
}
return TRUE;
}
I am using the following helpers within this function -
To add the correct ending to the statement strings:
function replaceEnd($string, $replacer = ';', $number_of_chars = 1) {
return left($string, strlen($string) - $number_of_chars) . $replacer;
}
To check, if $limit is reached which will lead to execution of the statement:
function checkInsert($sql, $sqlcount, $sql_limit) {
if ($sqlcount >= $sql_limit) {
$sql = replaceEND($sql);
query($sql);
$sqlcount = 0;
}
return $sqlcount;
}
To check for the last insert after the loop is finished:
function lastInsert($sql, $sql_insert = '') {
if (right($sql, 1) != ';') {
if ($sql != $sql_insert) {
$sql = replaceEND($sql);
query($sql);
return TRUE;
}
}
return FALSE;
}
Finally, to execute my statements:
function query($sql) {
$result = mysql_query($sql);
if ($result === FALSE) {
## Error Logging
}
return $result;
}
Basically, there is nothing wrong with these functions. But there is one problem, that I just could not solve: As you see, $limit is set to 1000 by default. This is usually perfectly fine, but when it comes to insert statements with much content / many characters per line of the insert statement, I have to reduce $limit manually in order to avoid errors. My question: does anyone know a way to automatically check if the current insert statement has reached the maximum in order to be executed correctly without wasting time by executing it too early? This would solve two problems at once: 1. I could get rid of $limit and 2. It would minimize the execution time needed to store the array into MySQL. I have just not found any approach to check the maximum possible length of a string that represents a MySQL insert statement, that I could apply before executing the statement...!?
for ($i=0; $i<=$gsayi-1; $i++)
{
$a[] = mysql_result($aylik,$i);
}
foreach ($a as $value)
{
$m = mysql_query("SELECT puan FROM sorular WHERE ID = $value");
echo $m;
}
a[ ] array is
2,2,1
I am trying to execute a mysql query with each of that values. I am using that values as ID.
I tried foreach loop but it shows me Resource id #7Resource id #7
How can I solve this problem?
You have to fetch the result
$m = mysql_query("SELECT puan FROM sorular WHERE ID = $value");
$result = mysql_fetch_assoc($m);
echo $result['puan'];
You have to get the results in some form.
http://php.net/manual/en/function.mysql-query.php
mysql_query returns a resource...not the results of the query. To get the results you have to use one of the mysql_fetch_* functions, in this example we fetch an object with the query results.
http://www.php.net/manual/en/function.mysql-fetch-object.php
Try something like this:
for ($i=0; $i<=$gsayi-1; $i++) {
$a[] = mysql_result($aylik,$i);
}
foreach ($a as $value) {
$result = mysql_query("SELECT puan FROM sorular WHERE ID = $value");
while($row = mysql_fetch_object($result) {
echo $value . ' = ' . $row->puan . ' | ';
}
}
I'm looping through some mysql results and need to add <span id=bottom></span> to each of them except the last row. What's the easiest way of doing this?
Will I have to count rows and then use a counter and an if/else statement? Or is there an easier method?
Try something like this:
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
{
$list[] = $row;
}
$lastItem = array_pop($list);
foreach($list as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
Not very short, but that would do the trick. Alternatively you could do what you suggested:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
for($i = 0; $i < $num-1; $i++) {
$element = mysql_fetch_assoc($result);
// echo here..
}
$item = mysql_fetch_assoc($result); // fetch last item..
Best wishes,
Fabian
I'm not a PHP expert, but can you put each row in an array? That way to know the length and you can loop through the array.
$result = mysql_query($sql);
$list = array();
while($row = mysql_fetch_assoc($result))
$list[] = $row;
foreach(array_slice($list, 0, -1) as $item) {
echo sprintf('<span id="bottom">%s</span>', $item['value']);
}
// do something with the last item..
You can avoid copying all the data before processing it if you fetch a record in advance before printing it (or the other way round: process the previously fetched record)
foreach( $pdo->query('SELECT x FROM foo') as $r) {
if ( isset($row) ) {
echo '<span>', $row['x'], '</span>';
}
$row = $r;
}
if ( isset($row) ) {
echo $row['x'];
}