I am using a class to generate a string name profile to slug and next use an SQL command to tell me whats the unique value to use in insert command, the problem is the command isn't working properly, sometimes it is possible to return a value which already exist...
Thats the class I am using to generate the slug: (composer require channaveer/slug)
And this the example code:
use Channaveer\Slug\Slug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
This is the content of the table when the script run:
Do you know how can I improve the select command to prevent it to return existing slugs from DB?
Ok finally found a solution... Heres the code for who wants to generate unique profile slugs using PHP - PDO and MySQL
$string = "John Doe";
$string = mb_strtolower(preg_replace('/\s+/', '-', $string));
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$pdo = Conectar();
$sql = "
SELECT slug_perfil
FROM advogados_e_escritorios
WHERE slug_perfil
LIKE '$slug%'
";
$statement = $pdo->prepare($sql);
if($statement->execute())
{
$total_row = $statement->rowCount();
if($total_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = $row['slug_perfil'];
}
if(in_array($slug, $data))
{
$count = 0;
while( in_array( ($slug . '-' . ++$count ), $data) );
$slug = $slug . '-' . $count;
}
}
}
echo $slug;
//john-doe-1
You should check if the slug exists or not from your database. If it already exists then you can append some random string like the following
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as #YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
I have followed the same for my blog articles (StackCoder) too. Even LinkedIn follows the same fashion.
Following is screenshot from LinkedIn URL
Related
I have column in table of database with value: PL TOFLEX NEGRO/PRETO
I search in my website: TOFLEX PRETO
I need output: PL TOFLEX NEGRO/PRETO
Can someone give me correct query to do this?
I try:
public function searchMaterial($nome)
{
$json = [];
$this->load->database();
if(!empty($this->input->get("q"))){
$this->db->like('nomeMaterial', $nome, 'both');
$query = $this->db->select('idMaterial as id,nomeMaterial as text')
->limit(50)
->get("material");
$json = $query->result();
}
echo json_encode($json);
}
but doesn't work.
You have to split your terms before querying your database.
I assume nomeMaterial is the name of your column.
Try this if you want your column contains BOTH terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->like('nomeMaterial', $term);
}
Or try this if you want your columns contains at least one of the terms :
$search = 'TOFLEX PRETO';
$terms = explode(' ',$search); //will return an array with two strings
foreach($terms as $term){
$this->db->or_like('nomeMaterial', $term);
}
I have one PHP script that reads from database and then generates JSON format string so that i can read on android device and show my covers and informations. The problem is how to add to each MySQL return index at end key name [SOURCE] = 'MYSOURCE4'?
Here is code that i im using:
while ($row = mysqli_fetch_assoc($qmovies)) {
$rows[] = $row;
$id = $row['id'];
switch(true) {
case $id > 4428:
$src = 'disk3.wuk';
break;
case $id > 2216:
$src = 'disk2.wuk';
break;
default:
$src = 'disk1.wuk';
break;
}
}
array_push($rows['0'], $src);
print json_encode($rows);
So i get this:
[{"id":"4457","title":"hahahah","source":"disk3.wuk"},{"id":"2000","title":"uuuuuu"}]
I need to get this:
[{"id":"4457","title":"hahahah","source":"disk3.wuk"},{"id":"2000","title":"uuuuuu","source":"disk2.wuk"}]
So how to add at end of MySQL read in while loop at each read end id array key and value source?
Thanks.
I am fetching a row count inside a repository and that query is returning an array as a result. How do i fetch the number count and display the result in my twig file?
This is the query fetching row count:
public function getTrailCount(){
$sql = "SELECT count(`id`) FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
//$trailCount->getSingleScalarResult();
//echo '<pre>'; print_r($trailCount); exit;
return $trailCount;
}
In controller i am trying to fetch it like this, i know its a wrong procedure though:
foreach($trailCount as $trail){
$data['trailCount'] = $trail->count; //throughing an error
}
How to mend this code, any help is much appreciated. Thanks
In that case, using PDO::FETCH_NUM would be much simpler:
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
...
foreach($trailCount as $trail){
$data['trailCount'] = $trail[0]; // Using "0" instead of named key
}
But if you still really want to use FETCH_ASSOC you would need:
$sql = "SELECT count(`id`) as cnt FROM `article ...... "
.....
foreach($trailCount as $trail){
$data['trailCount'] = $trail['cnt'];
}
Notice that I'm not using ->cnt but ['cnt'] since data returned from PDO is not object-based but array-bases instead.
Hope this helps a bit...
EDIT:
Given the lack of Twig part, I can only assume what you're trying to do:
/**
* #Route("/foo")
* #Template()
*/
public function fooAction(){
...
... The code above
...
return array('data' => $data);
}
And then, in your twig:
{{ data.trailCount }}
I got the solution with some help of Jovan Perovic, i did like this:
The query Part:
public function getTrailCount(){
$sql = "SELECT count(`id`) as cnt FROM `article` where `publish`='1' AND `catForFilter` like '%trail%' ";
$stmt = $this->connection->prepare($sql);
$stmt->execute();
$trailCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $trailCount[0]['cnt']; //instead of an array i passed the single value
}
in controller:
$trailCount = $clicknblog->getTrailCount();
return $this->render('AdventureBiddingBundle:Organiser:editProfileOrganiser.html.twig', array(
'trails' => $trailCount
));
in twig file i displayed the value directly:
<p>{{ trails }}</p>
Hope this helps to someone with same problem
theoretically I'll show you the code that works, I mean, it makes sense but I can not get no change in the table! : \
so, here is the code:
else if ($mode == 'password') {
$generated_password = substr(md5(rand(999,999999)), 0, 8);
change_password($user_data['user_id'],$generated_password);
update_user($user_data['user_id'], array('password_recover' => '1'));
email($email, 'Your new password', "Hi," . $user_data['nome'] . " \n\nYour new password is: " . $generated_password . "");
}
Functions:
function update_user($user_id,$update_data){
$update = array();
array_walk($update_data, 'array_sanitize');
foreach($update_data as $field => $data) {
$update[]='`' .$field. '`=\'' .$data . '\'';
}
mysql_query("UPDATE users SET " . implode(', ',$update) . "WHERE user_id = '$user_id'");
}
function change_password($user_id,$password) {
$user_id = (int) $user_id;
$password = md5($password);
mysql_query("UPDATE users SET password = '$password' WHERE user_id = $user_id");
}
I have not even written the email function because that works. Thanks in advance! :)
You should add some kind of error handling to your code. At least add or die('Error: '.mysql_error()) after each mysql_query() to at least get some idea of what went wrong when the queries are executed.
And if you just take code from somewhere and don't really understand what it does, don't be surprised, if it doesn't do what you want it to do.
I've a MySql table where I put some value: id, name of opportunity, category of opportunity, commission etc etc. Now I need to create (automatically) a shortcode that call these value win an array, so for example if i write [opportunity id="1"] wordpress display banner of the opportunity in the database that have id=1.
This is my code
function opportunity_banner_shortcode($atts) {
extract(shortcode_atts(array("id" => ''), $atts));
global $table_prefix, $wpdb, $user_level;
$table_name = $table_prefix . "opportunities";
$finds = $wpdb->get_results("SELECT * FROM {$table_name}", ARRAY_A);
if(sizeof($finds)){
foreach($finds as $find)
return "<a href='" . $find["opp_link"].
"'><img src='" . $find["opp_banner_preview"]."'></a> ";
}
}
add_shortcode('opportunity', 'opportunity_banner_shortcode');
Thanks to all
Maybe the query should be
$finds = $wpdb->get_results("SELECT * FROM {$table_name} WHERE id={$id}",
ARRAY_A);