0

I need to update the column of a table.

I have this:

ID | title | slug_name


1 | The Winner is |


2 | Beautiful day |


I've to update the slug_name:

ID | title | slug_name


1 | The Winner is | the-winner-is


2 | Beautiful day | beautiful-day


So I created a function slug()

function slug($str) {
    return strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $str), '-'));
}

and how can I return "title" in the function "slug"?

mysql_query("UPDATE table SET slug_name = '".slug(???title???)."'");

I tried also:

$items = mysql_query("SELECT title FROM table");
while($item = mysql_fetch_object($items)) {
    mysql_query("UPDATE table SET slug_name = '".slug($item->title)."'");
}

But all rows return the same "slug_name".

Erfo
  • 37
  • 1
  • 8

1 Answers1

0

you have a missing parameter, in order that MySQL updates and specific row, you need to specify that row attribute Either the ID or title with a WHERE closure in your function.

    function slug($str) {
    return "UPDATE table SET slug_name ='" . strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $str), '-')) . "' WHERE title ='" . $str . "'";
}

Now make it Clean:

   function slug($str) {
    $new_string  = "UPDATE table SET slug_name ='";
    $new_string .= strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $str), '-'));
    $new_string .=  "' WHERE title ='" . $str . "'";
    return $new_str
}
  • After replace function slug() with your function, I've to paste this? `$items = mysql_query("SELECT title FROM table"); while($item = mysql_fetch_object($items)) { mysql_query("UPDATE table SET slug_name = '".slug($item->title)."'"); }` – Erfo May 09 '16 at 20:44