S. Martin
S. Martin

Reputation: 47

PHP: Translating MySQL to Postgresql

I need to translate the following MySQL sentences in PHP to Postgresql

Config.php File

MySQL

$mysqli = new mysqli($db_host, $db_username, $db_password, $db_name);

I tried: (Postgresql)

$db = pg_connect($db_host, $db_username, $db_password, $db_name);

MySQL:

$get_total_rows = 0;
$results = $mysqli->query("SELECT COUNT(*) FROM menu");

if($results){
$get_total_rows = $results->fetch_row(); 
}
//break total records into pages
$total_groups= ceil($get_total_rows[0]/$items_per_group);

I tried: (Postgresql) I don't know if I need really to change anything, I just change the name of my variable since it is different in my config.php file

$get_total_rows = 0;
$results = $db->query("SELECT COUNT(*) FROM menu");

if($results){
$get_total_rows = $results->fetch_row(); 
}
//break total records into pages
$total_groups= ceil($get_total_rows[0]/$items_per_group);

MySQL

if($_POST)
{
//sanitize post value
$group_number = filter_var($_POST["group_no"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

//throw HTTP error if group number is not valid
if(!is_numeric($group_number)){
    header('HTTP/1.1 500 Invalid number!');
    exit();
}

//get current starting point of records
$position = ($group_number * $items_per_group);


//Limit our results within a specified range. 
$results = $mysqli->prepare("SELECT id, name, message FROM paginate ORDER BY id ASC LIMIT $position, $items_per_group");
$results->execute(); //Execute prepared Query
$results->bind_result($id, $name, $message); //bind variables to prepared statement


echo '<ul class="page_result">';
while($results->fetch()){ //fetch values
    echo '<li id="item_'.$id.'"><span class="page_name">'.$id.') '.$name.'</span><span class="page_message">'.$message.'</span></li>';  
}
echo '</ul>';

$mysqli->close();
}

Have not idea how to put this into Postgresql

Thank you so much

Upvotes: 1

Views: 1689

Answers (1)

Anthony E
Anthony E

Reputation: 11235

MySQL and Postgres both use a SQL dialect, so many of your MySQL queries will work, though Postgres is a bit more strict and consistent than MySQL. There's no automatic way to do this conversion, however. In fact, looking through your code it appears these queries should work in Postgres as well. Long term you might want to consider using an ORM to make these sorts of migrations easier.

I'd recommend implementing unit tests for all of your queries work before making the change. This way you can ensure correct results when you switch to Postgres.

Upvotes: 1

Related Questions