Posted on Leave a comment

MySQL connection string with PHP and others

A MySQL connection string is a string of parameters and values used to establish a connection between a client application and a MySQL database server. It contains the necessary information to identify the server, authenticate the user, and specify additional connection options.

The exact format of a MySQL connection string can vary depending on the programming language or framework being used. However, it typically includes the following components:

  1. Server/Host: This specifies the hostname or IP address of the machine where the MySQL server is running. For example, localhost or 127.0.0.1.
  2. Port: This indicates the port number on which the MySQL server is listening for incoming connections. The default port for MySQL is 3306, but it can be configured differently.
  3. Database: This specifies the name of the database you want to connect to or perform operations on.
  4. User: This specifies the username used to authenticate with the MySQL server.
  5. Password: This is the password associated with the username for authentication.

Here’s an example of a MySQL connection string in the commonly used format:

Hostlocalhost / 127.0.0.1 (depending on language and/or connection method used)
Port3306
Usernameroot
Passwordroot
Socket/Applications/MAMP/tmp/mysql/mysql.sock
This connection method can be changed by your local network configuration.

PHP

<?php
  $db_host = 'localhost';
  $db_user = 'root';
  $db_password = 'root';
  $db_db = 'information_schema';
 
  $mysqli = @new mysqli(
    $db_host,
    $db_user,
    $db_password,
    $db_db
  );
	
  if ($mysqli->connect_error) {
    echo 'Errno: '.$mysqli->connect_errno;
    echo '<br>';
    echo 'Error: '.$mysqli->connect_error;
    exit();
  }

  echo 'Success: A proper connection to MySQL was made.';
  echo '<br>';
  echo 'Host information: '.$mysqli->host_info;
  echo '<br>';
  echo 'Protocol version: '.$mysqli->protocol_version;

  $mysqli->close();
?>

2. Connect via network
<?php
  $db_host = '127.0.0.1';
  $db_user = 'root';
  $db_password = 'root';
  $db_db = 'information_schema';
  $db_port = 3306;

  $mysqli = new mysqli(
    $db_host,
    $db_user,
    $db_password,
    $db_db,
	$db_port
  );
	
  if ($mysqli->connect_error) {
    echo 'Errno: '.$mysqli->connect_errno;
    echo '<br>';
    echo 'Error: '.$mysqli->connect_error;
    exit();
  }

  echo 'Success: A proper connection to MySQL was made.';
  echo '<br>';
  echo 'Host information: '.$mysqli->host_info;
  echo '<br>';
  echo 'Protocol version: '.$mysqli->protocol_version;

  $mysqli->close();
?>

Python

1. Connect using an UNIX socket (preferred)
#!/usr/bin/env /Applications/MAMP/Library/bin/python

import mysql.connector

config = {
  'user': 'root',
  'password': 'root',
  'host': 'localhost',
  'unix_socket': '/Applications/MAMP/tmp/mysql/mysql.sock',
  'database': 'test',
  'raise_on_warnings': True
}

cnx = mysql.connector.connect(**config)

cursor = cnx.cursor(dictionary=True)

cursor.execute('SELECT `id`, `name` FROM `test`')

results = cursor.fetchall()

for row in results:
  id = row['id']
  title = row['name']
  print '%s | %s' % (id, title)

cnx.close()

2. Connect via network
#!/usr/bin/env /Applications/MAMP/Library/bin/python

import mysql.connector

config = {
  'user': 'root',
  'password': 'root',
  'host': '127.0.0.1',
  'port': 3306,
  'database': 'test',
  'raise_on_warnings': True
}

cnx = mysql.connector.connect(**config)

cursor = cnx.cursor(dictionary=True)

cursor.execute('SELECT `id`, `name` FROM `test`')

results = cursor.fetchall()

for row in results:
  id = row['id']
  title = row['name']
  print '%s | %s' % (id, title)

cnx.close()

Perl

Connect using an UNIX socket (preferred)
#!/Applications/MAMP/Library/bin/perl
use strict;
use warnings;
use DBI;

print "Content-type: text/html\n\n";

my $source = 'DBI:mysql:database=test;host=localhost;mysql_socket=/Applications/MAMP/tmp/mysql/mysql.sock';
my $user = 'root';
my $password = 'root';

my $attr = {
  PrintError => 0, # turn off error reporting via warn()
  RaiseError => 1, # turn on error reporting via die()
};

my $dbc = DBI->connect($source, $user, $password, $attr)
or die "Unable to connect to mysql: $DBI::errstr\n";

my $sql = $dbc->prepare("SELECT `id`, `name` FROM `test`");
my $out = $sql->execute()
or die "Unable to execute sql: $sql->errstr";

while ((my $id, my $name) = $sql->fetchrow_array()) {
  print "id: $id / name: $name<br>\n";
}

$dbc->disconnect();

Connect via network
#!/Applications/MAMP/Library/bin/perl
use strict;
use warnings;
use DBI;

print "Content-type: text/html\n\n";

my $source = 'DBI:mysql:database=test;host=localhost;port=3306';
my $user = 'root';
my $password = 'root';

my $attr = {
  PrintError => 0, # turn off error reporting via warn()
  RaiseError => 1, # turn on error reporting via die()
};

my $dbc = DBI->connect($source, $user, $password, $attr)
or die "Unable to connect to mysql: $DBI::errstr\n";

my $sql = $dbc->prepare("SELECT `id`, `name` FROM `test`");
my $out = $sql->execute()
or die "Unable to execute sql: $sql->errstr";

while ((my $id, my $name) = $sql->fetchrow_array()) {
  print "id: $id / name: $name<br>\n";
}

$dbc->disconnect();

Ruby

Connect using an UNIX socket (preferred)
#!/Applications/MAMP/Library/bin/ruby

require "mysql2"

@db_host = "localhost"
@db_socket = "/Applications/MAMP/tmp/mysql/mysql.sock"
@db_user = "root"
@db_pass = "root"
@db_name = "test"

client = Mysql2::Client.new(
  :host => @db_host,
  :socket => @db_socket,
  :username => @db_user,
  :password => @db_pass,
  :database => @db_name
)

result = client.query("SELECT * from `test`")

result.each do |row|
  puts row["id"].to_s() + " | " + row["name"].to_s()
end

client.close

Connect via network
#!/Applications/MAMP/Library/bin/ruby

require "mysql2"

@db_host = "localhost"
@db_port = 3306
@db_user = "root"
@db_pass = "root"
@db_name = "test"

client = Mysql2::Client.new(
  :host => @db_host,
  :port => @db_port,
  :username => @db_user,
  :password => @db_pass,
  :database => @db_name
)

result = client.query("SELECT * from `test`")

result.each do |row|
  puts row["id"].to_s() + " | " + row["name"].to_s()
end

client.close

MySQLi

<?php
  $db = new SQLite3('/Applications/MAMP/db/sqlite/mydb.db');
  $db->exec("CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT)");
  $db->exec("INSERT INTO items(name) VALUES('Name 1')");
  $db->exec("INSERT INTO items(name) VALUES('Name 2')");

  $last_row_id = $db->lastInsertRowID();

  echo 'The last inserted row ID is '.$last_row_id.'.';

  $result = $db->query('SELECT * FROM items');

  while ($row = $result->fetchArray()) {
    echo '<br>';
    echo 'id: '.$row['id'].' / name: '.$row['name'];
  }

  $db->exec('DELETE FROM items');

  $changes = $db->changes();

  echo '<br>';
  echo 'The DELETE statement removed '.$changes.' rows.';
?>

Note that all connections string above are using MAMP Pro for test. To learn more about MAMP or MAMP Pro, please click here. The actual syntax and format of the connection string may vary depending on the programming language or framework you are using.

Posted on Leave a comment

How to get post view count in WordPress?

In WordPress, the term “post view count” refers to the number of times a specific post or page has been viewed by visitors on your website. It is a metric used to measure the popularity or engagement of a particular piece of content.

Post view count is typically tracked and displayed using plugins or tracking tools specifically designed for WordPress. These plugins integrate with your website and keep a record of the number of times a post or page has been accessed.

To get the post view count in WordPress, you can use a combination of WordPress functions and plugins. Here are two methods you can try:

Method 1: Using a Plugin (such as “Post Views Counter”):

  1. Install and activate the “Post Views Counter” plugin from the WordPress Plugin Directory.
  2. Once activated, the plugin will automatically start tracking the view count for your posts.
  3. To display the view count on your posts, you can use a shortcode provided by the plugin. Edit your post or page and add the shortcode [post-views] to the desired location. This will display the view count when the post is viewed.

Method 2: Manual Implementation:

  1. Open your theme’s functions.php file for editing. You can find this file in your WordPress theme’s directory.
  2. Add the following one of functions code below to the functions.php file:
function get_post_view_count($post_id) {
    $count_key = 'post_views_count';
    $count = get_post_meta($post_id, $count_key, true);
    if ($count == '') {
        delete_post_meta($post_id, $count_key);
        add_post_meta($post_id, $count_key, '0');
        return "0";
    }
    return $count;
}

function set_post_view_count($post_id) {
    $count_key = 'post_views_count';
    $count = get_post_meta($post_id, $count_key, true);
    if ($count == '') {
        $count = 0;
        delete_post_meta($post_id, $count_key);
        add_post_meta($post_id, $count_key, '0');
    } else {
        $count++;
        update_post_meta($post_id, $count_key, $count);
    }
}

// Add the following code where you want to display the view count, e.g., single.php, content.php, etc.
$post_id = get_the_ID();
set_post_view_count($post_id);
$view_count = get_post_view_count($post_id);
echo 'Post Views: ' . $view_count;
  1. Save the functions.php file and upload it back to your server.
  2. The code will update the view count whenever a post is viewed, and you can display the view count using the provided echo statement.

Note: If you’re not comfortable editing theme files directly, you can use a child theme or a custom plugin to add the code instead.

Remember to backup your theme files or create a child theme before making any changes to avoid losing your modifications in case of future theme updates.

Posted on Leave a comment

Display Bootstrap Carousel with WordPress

What is Carousel?

The carousel is a slideshow for cycling through a series of content, built with CSS 3D transforms and a bit of JavaScript. It works with a series of images, text, or custom markup. It also includes support for previous/next controls and indicators.

Read more document about carousel here: https://getbootstrap.com/docs/5.2/components/carousel/

Note: Bootstrap Carousel will start its work from two contents so you need to create at least two WordPress post to testing your work. If you want your slideshow to slide only your specific post or Featured Post, please see here how to create Feature Post or Sticky Post, please see here how to get your WordPress sticky post.

Here! we have already implemented Bootstrap Carousel and WordPress as below:

<?php
$last_posts = new WP_Query( array(
    'post_type'           => 'post',
    'posts_per_page'      => 4,
    'post_status'  => 'publish',
    'post__not_in' => get_option('sticky_posts'),
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'name',
            'terms'    => 'Featured',
        ),
    ),
    'orderby'             => 'rand',
    'order'               => 'desc'
) );
?>
<section class="py-5 bg-light border-bottom border-top">
    <div class="container-fluid px-3">
    <div class="row row-cols-2">
     <?php
        if ( is_active_sidebar( 'suostei_featured_ad' ) ) :
            $cols_first = "col-lg-8";
            $cols_second = "col-lg-4";
        else:
            $cols_first = "col-lg-12";
            $cols_second = "col-lg-12";
        endif;
     ?>
     <div class="<?php echo $cols_first;?> col-md-12 col-sm-12 col-12">
         <div id="quickButton" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-indicators">
              <button type="button" data-bs-target="#quickButton" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
              <button type="button" data-bs-target="#quickButton" data-bs-slide-to="1" aria-label="Slide 2"></button>
              <button type="button" data-bs-target="#quickButton" data-bs-slide-to="2" aria-label="Slide 3"></button>
              <button type="button" data-bs-target="#quickButton" data-bs-slide-to="3" aria-label="Slide 4"></button>
            </div>
                <div class="carousel-inner h-100">
                  <?php 
                    if ($last_posts->have_posts()): 
                        $last_posts->the_post();
                            if (has_post_thumbnail()):
                                $post_thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $last_posts->ID ),'full');
                            else:
                                $post_thumbnail = array(suostei_theme_uri.'/assets/noimage.jpg','');
                            endif;
                    ?>
                    <div class="carousel-item active">
                        <div class="row g-0 overflow-hidden flex-md-row mb-1 h-100 w-100 position-relative">
                        <div class="card card-cover h-100 overflow-hidden text-bg-dark" style="background-image: url('<?php echo $post_thumbnail[0];?>');">
                            <div class="col p-4 d-flex flex-column position-static text-shadow-1 bg-dark bg-opacity-50">
                                <h4 class="mb-0 lh-base card-text text-center p-3 display-6"><a class="link-info" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                                <hr/>
                                <p class="card-text text-center mb-auto overflow-hidden p-5 pb-lg-5 pt-lg-4 px-lg-5 h-100 carousel-caption-size"><?php echo suostei_excerpt();?></p>
                                <hr/>
                                <div class="d-flex justify-content-between d-block">
                                    <p class="p-0">
                                       <?php 
                                            $categories = get_the_category($last_posts->ID);
                                            if ( ! empty( $categories ) ) {
                                                echo '<a class="link-info" href="'.esc_attr(esc_url(get_category_link($categories[0]->term_id))).'">'.esc_html( $categories[0]->name ).'</a>';	
                                            }
                                        ?>
                                    </p>
                                    <div class="mb-1 text-info text-end p-0">
                                        <time datetime="<?php echo get_the_date('c'); ?>" itemprop="datePublished">
                                            <?php 
                                                echo get_the_date($last_posts->ID);
                                            ?>
                                        </time>
                                    </div>
                                    <p class="p-0">
                                        <a class="float-end link-info" onClick="window.location.href='<?php the_permalink();?>'" type="button" class="btn btn-primary btn-lg px-4 me-md-2"><i class="fas fa-book-open-reader"></i> <?php echo readmore;?></a>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
                <?php endif;?>
                <?php while ($last_posts->have_posts()): 
                    $last_posts->the_post();
                        if (has_post_thumbnail()):
                            $post_thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $last_posts->ID ),'full');
                         else:
                            $post_thumbnail = array(suostei_theme_uri.'/assets/noimage.jpg','');
                         endif;
                ?>
                <div class="carousel-item">
                    <div class="row g-0 overflow-hidden flex-md-row mb-1 h-100 w-100 position-relative">
                        <div class="card card-cover h-100 overflow-hidden text-bg-dark" style="background-image: url('<?php echo $post_thumbnail[0];?>');">
                            <div class="col p-4 d-flex flex-column position-static text-shadow-1 bg-dark bg-opacity-50">
                                <h4 class="mb-0 lh-base card-text text-center p-3 display-6"><a class="link-info" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
                                <hr/>
                                <p class="card-text text-center mb-auto overflow-hidden p-5 pb-lg-5 pt-lg-4 px-lg-5 h-100 carousel-caption-size"><?php echo suostei_excerpt();?></p>
                                <hr/>
                                <div class="d-flex justify-content-between d-block">
                                    <p class="p-0">
                                       <?php 
                                            $categories = get_the_category($last_posts->ID);
                                            if ( ! empty( $categories ) ) {
                                                echo '<a class="link-info" href="'.esc_attr(esc_url(get_category_link($categories[0]->term_id))).'">'.esc_html( $categories[0]->name ).'</a>';	
                                            }
                                        ?>
                                    </p>
                                    <div class="mb-1 text-info text-end p-0">
                                        <time datetime="<?php echo get_the_date('c'); ?>" itemprop="datePublished">
                                            <?php 
                                                echo get_the_date($last_posts->ID);
                                            ?>
                                        </time>
                                    </div>
                                    <p class="p-0">
                                        <a class="float-end link-info" onClick="window.location.href='<?php the_permalink();?>'" type="button" class="btn btn-primary btn-lg px-4 me-md-2"><i class="fas fa-book-open-reader"></i> <?php echo readmore;?></a>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endwhile;?>
                </div>
                <button class="carousel-control-prev" type="button" data-bs-target="#quickButton" data-bs-slide="prev">
                  <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                  <span class="visually-hidden">Previous</span>
                </button>
                <button class="carousel-control-next" type="button" data-bs-target="#quickButton" data-bs-slide="next">
                  <span class="carousel-control-next-icon" aria-hidden="true"></span>
                  <span class="visually-hidden">Next</span>
                </button>
            </div>
         </div>

     <div class="<?php echo $cols_second;?> col-md-12 col-sm-12 col-12">
         <div class="d-flex justify-content-center">
            <?php do_action('_featured_ads');?>
        </div>
     </div>
 </div>
    </div>
</section>

Please remember that the example code above is working fine with Bootstrap 5.2.2 and WordPress 6.2. Enjoy!

Posted on Leave a comment

Create Feature Post in WordPress

The first thing you should know is that Featured Post has not been available in WordPress for a long time. But we can still create it ourselves by writing query from our tags or categories names.

  1. You just create a post as simple as you can.
  2. Create tag name as “Featured” then add into your recently post.
  3. Implement some codes to call it or just copy the code below:
<?php
$last_posts = new WP_Query( array(
    'post_type'           => 'post',
    'posts_per_page'      => 1,
    'post_status'  => 'publish',
    'post__not_in' => get_option('sticky_posts'),
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'name',
            'terms'    => 'Featured',
        ),
    ),
    'orderby'             => 'rand',
    'order'               => 'desc'
) );
if($last_posts->have_posts()):
    $last_posts->the_post();
    //display your code loop here
endif;
?>

That’s it. If you like this post, please give us some thumbs up.

Posted on Leave a comment

Get sticky post – WordPress

Sticky Post is a method used to capture any post, put it in a convenient place for visitors to see every time they visit the site.

Sticky Post has been used since the old WordPress version until now. It is useful and easy to capture the attention of website visitors.

For web developers using WordPress and PHP forms, here is an easy example to implement Sticky Post. Please follow or copy the code below.

<?php
$sticky = get_option('sticky_posts');
if (!empty($sticky)){
    echo '<section class="py-5 text-center container">';
    echo '<div class="row py-lg-5">';
    rsort($sticky);
    $args = array(
        'posts_per_page' => 1,
        'post_status'  => 'publish',
        'post__in' => $sticky,
        'orderby' => 'rand',
        'order'  => 'desc'
    );
    $sticky_post =  new WP_Query($args);
    if ($sticky_post->have_posts()) {
         $sticky_post->the_post();
        ?>
        <div class="col-lg-6 col-md-8 mx-auto">
            <h1 class="fw-light display-6 lh-base"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
            <p class="lead text-muted">
                <?php echo the_excerpt();?>
            </p>
            <p>
              <a href="<?php the_permalink(); ?>" class="btn btn-primary my-2"><i class="fas fa-book-open-reader"></i></a>
              <a href="#more" class="btn btn-secondary my-2"><i class="fas fa-list-alt"></i></a>
            </p>
        </div>
        <?php
    }
    echo '</div>';
    echo '</section>';
}
?>

What you need to see just a few lines below:

$sticky = get_option('sticky_posts');
if (!empty($sticky)){
    echo '<section class="py-5 text-center container">';
    echo '<div class="row py-lg-5">';
    rsort($sticky);
    $args = array(
        'posts_per_page' => 1,
        'post_status'  => 'publish',
        'post__in' => $sticky,
        'orderby' => 'rand',
        'order'  => 'desc'
    );
}

And one more step is to modify your post as Sticky content in your wordpress post dashboard. It is just very simple by only tick on the “Make the post sticky”.

Enjoy!

Posted on Leave a comment

Get posts by category id – wordpress

If you want to get posts from WordPress through Category Id, there are many ways to do so. Visit the WordPress tutorial page to learn more. But here we will show you how easy one by following the example code below:

<div class="container">
<?php
$categories = get_the_category();
$category_id = $categories[0]->term_id;
echo '<h2 class="pb-2 border-bottom">'.$categories[0]->name.'</h2>';
echo '<div class="row row-cols-1 row-cols-lg-1 align-items-stretch py-5">';
$last_posts = new WP_Query( array(
    'post_type'           => 'post',
    'category__in'  => $category_id,
    'post_status'  => 'publish',
    'posts_per_page'      => 12,
    //'orderby'             => 'name',
    'order'               => 'desc'
) );
if($last_posts->have_posts()):?>
<div class="list-group w-auto">
<?php
while ($last_posts->have_posts()):
    $last_posts->the_post();
     if (has_post_thumbnail()):
        $post_thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $last_posts->ID ),'full');
     else:
        $post_thumbnail = array(suostei_theme_uri.'/assets/noimage.jpg','');
     endif;
    ?>
        <div class="d-flex gap-2 w-100 justify-content-between mb-3">
            <div>
              <h4 class="mb-3 text-primary"><a class="link-info" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
              
              <p class="mb-2 text-small"><?php echo gen_string_tiny(suostei_excerpt());?></p>
              <small class="text-nowrap">
                  <time datetime="<?php echo get_the_date('c'); ?>" itemprop="datePublished"><?php echo get_the_date($last_posts->ID); ?></time>
                  <!--<time datetime="<?php echo get_the_date('c'); ?>" itemprop="datePublished"><?php echo get_the_date(); ?></time>--> 
                  <span class="float-end">
                      
                      <?php 
                        $categories = get_the_category($last_posts->ID);
                        if ( ! empty( $categories ) ) {
                           echo '<a href="'.esc_attr(esc_url(get_category_link($categories[0]->term_id))).'">'.esc_html( $categories[0]->name ).'</a>';		
                        }
                      ?>

                  </span>
              </small>
            </div>
        </div>
    <hr/>
    <?php 
    endwhile;
    ?>
</div>
    <div class="col-lg-12 mb-1 mt-3 pt-3">
       <?php do_action('post_pagination');?>
    </div>
    <?php
    endif;
    echo '</div>';
    ?>
</div>


Please notice that, you need to change some variable that are using here by replace with your desire. The best part you need to see is look like below:

<?php
$categories = get_the_category();
$category_id = $categories[0]->term_id;
$last_posts = new WP_Query( array(
    'post_type'           => 'post',
    'category__in'  => $category_id,
    'post_status'  => 'publish',
    'posts_per_page'      => 12,
    //'orderby'             => 'name',
    'order'               => 'desc'
) );
?>

That’s it! this code is working fine for wordpress 4.5 and above.