pg_query returns nothing - php

Newbie question about PostgreSQL. I'm migrating a MySQL/PHP app I've created, hosted on a Linux server, to PostgreSQL/PHP on a MacOSX Lion Server environment. It's my first experience with Postgres. The first query I'm testing doesn't work as it returns nothing (not even an error message, whichever check code I add). What did I do wrong? I've read articles on the web including the doc on php official website but all comments, personal methods and differences from version to version, either with Postgres or PHP, make it very confusing and I eventually don't understand exactly show I should write my query and fetch_array. Thanks for any suggestions.
Here is my code from the original MySQL application:
// below is the "connexion.php" file
function connexion ()
{
$link=#mysql_connect ("localhost","username","pwd");
if ($link && mysql_select_db ("database"))
return ($link);
return (FALSE);
}
// below is the "index.php" file
require ("connexion.php");
connexion() or exit();
$reqcount = mysql_query ("SELECT * FROM people");
$result = mysql_num_rows($reqcount);
echo "Total : ".$result." people";
mysql_free_result ($reqcount);
mysql_query("set names 'utf8'");
$reqcat = mysql_query ("SELECT catname FROM categories ORDER BY catname");
while ($fieldcat = mysql_fetch_array($reqcat))
{
$name = $fieldcat[catname];
echo $name."<br>";
}
mysql_free_result ($reqcat);
mysql_close ();
And here is the PostgreSQL adaptation:
// connexion.php
function connexion ()
{
$link=pg_connect("host=localhost port=5432 dbname=database user=username password=pwd connect_timeout=5 options='--client_encoding=UTF8'");
return ($link);
}
// index.php
require ("connexion.php");
$reqcount = pg_query ($link,"SELECT * FROM people");
$result = pg_num_rows($reqcount);
echo "Total : ".$result." people";
pg_free_result ($reqcount);
$reqcat = pg_query ($link,"SELECT catname FROM categories ORDER BY catname");
while ($fieldcat = pg_fetch_array($reqcat))
{
$name = $fieldcat[catname];
echo $name."<br>";
}
pg_free_result ($reqcat);
pg_close ();

The php code for postgresql doesn't call connexion() so it never connects, unlike the mysql code.

You can try your query if it fails display error
$reqcount = pg_query ($link,"SELECT catname FROM people") or die(pg_last_error());
This way you can see your error.
errors
UPDATE:
Remove the # in your connection to see the error, and add or die(pg_last_error())
to see the error

Related

How do I obtain data through a MySQL Database using GET in PHP?

I've tried the solutions in this question, however mysql has been depricated for mysqli. Even with these changes it still doesn't return the information, instead returns an error, with nothing else (Nothing is heard from mysqli)
What i'm trying to do is kind of similar to the question linked, however it would look like this in the url: example.com?view-work=A01 It would search for A01 in the database, then return the Name, description, an image URL and date it was made live.
This is the code that i've been able to make using the answers from the question:
<?php
//Establishing a connection to the Artwork Database
mysqli_connect('localhost', 'dbuser', 'dbpassword');
mysqli_select_db('db');
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_real_escape_string($artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($sql);
if (!$result) {
echo "Something's gone wrong! ".mysqli_error();
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>
Seems like the cause of these errors was my own incompetence, also probably the fact I'm kind of new to PHP and MySQL in general. I learnt that I needed to reference my connection in some of the commands for them to successfuly process after adding the debug exception mentioned in the OP's comments.
As someone also pointed out, Yes this code is still vulnerable to other types of SQL injection, I'll be addressing these before the final version of the code goes live.
Fixed Code:
<?php
//Establishing a connection to the Artwork Database
$link = mysqli_connect('localhost', 'dbusr', 'dbpasswd', 'db');
//Exeptional Debugging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (!$link) {
echo "Error: Unable to connect to MySQL!";
echo "Error No.".mysqli_connect_errno();
echo "Error in question: ".mysqli_connect_error();
exit;
}
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_escape_string($link, $artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($link, $sql);
if (!$result) {
echo "Something's gone wrong!"; //This line will be changed later to sound more professional
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

Fetching the data from sqlite3 database in php

I need some help with my PHP. I have a trouble with fetching the data from the database. I have hired a PHP developer who did not do his job properly that he have messed up the code which make it don't work so I need some help to fix the issue to get it working again.
When I try this:
//open the database File
$db = new SQLite3('myChannel.db');
if(!$db)
{
echo $db->lastErrorMsg();
}
else
{
$channel_name = $_GET['channels'];
$sql ="SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='$channel_name'";
$results = $db->query($sql);
while ($row = $results->fetchArray())
{
print_r($row);
}
What happen with the code is it will not fetching the matched data from the database as it will not do anything. I think there is something wrong with the $sql variable.
What I'm expecting to do is I want to look for data in the database where I use the variable called $channel_name, then I want to fetch the matched data to output them in my PHP.
Can you please help me how I can fetch the matched data in the database?
Try this code based on the SQLite PHP docs
class MyDB extends SQLite3 {
function __construct() {
$this->open('myChannel.db');
}
}
$db = new MyDB();
if (!$db) {
echo $db->lastErrorMsg();
} else {
$channel_name = $_GET['channels'];
$sql = "SELECT channel, title, start_date, stop_date, description FROM programs WHERE channel='{$channel_name}'";
$results = $db->query($sql);
while($row = $results->fetchArray(SQLITE3_ASSOC) ) {
print_r($row);
}
}
I changed a few things. I turned your database connection into a class, and I changed your while to include SQLITE3_ASSOC.
Warning: OP's code and as a result this answer has code that is
vulnerable to SQL Injection!

Php Custom Function For Mysql Query Not Working

I have created two functions one for connecting to MySQL database and one for running a specific query.
I enter the database name as parameter for first function to connect to the database, this works fine, but my problem is with the second one.
2nd function returns the $result from running a query, but when I use mysql_fetch_array with the $result, it gives one output even if it supposed to give more than one.
As I am no php expert so i can't find the solution. Please help me.
Here is the code:
File Function.php
<?php
function myconnect($data)
{
$db_host='localhost';
$db_user='root';
$db_pwd='';
$data=$data;
$dbc = mysqli_connect($db_host, $db_user,$db_pwd,$data) or die (mysql_error());
return $dbc;
}
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
$query="SELECT *FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC";
$result = mysqli_query($dbc, $query);
return $result;
}
?>
File test.php
<?php
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
//runquery('database','table','col','id')/
while($row=mysqli_fetch_array($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}
?>
If I am doing all wrong then suggest me a better way :-)
A quick glance shows that in your function runquery
SELECT *FROM
should be
SELECT * FROM
note the space after the *
EDIT :
I also notice you are using *mysqli_fetch_array* and this is not a valid mysqli method. You are right in using the mysqli extension over mysql but you should look more into statement fetch to solve this issue. The link I provided give a procedural example that should work for what you need.
function myconnect($db)
{
/*Removed redundant - single use variables*/
/*DB name was passed to the client_flags parameter of mysql_connect instead of mysql_select_db*/
$dbc = mysql_connect("localhost", "root","") or die (mysql_error());
/*Inserted Line*/
mysql_select_db($data);
return $dbc;
}
Currently you're not selecting a database - equivalent of USE DATABASE db_name.
Couple of syntax changes and function definition
function runquery($db,$table,$tcol,$tid)//(databse,table,column_name,identifier)
{
$dbc=myconnect($db);
/*Query and link identifier were in the wrong order*/
return mysql_query("SELECT * FROM ".$table." WHERE ".$tcol."=".$tid." ORDER BY first_name ASC", $doc);
}
Finally a couple of syntax changes, function calls
require_once('testfunc.php');
$result= runquery('user','user_basic','user_type','1');
/*fetch associateive array of result during iteration*/
while($row=mysql_fetch_assoc($result))
{
echo '<strong>First Name:</strong>' . $row['first_name'] . '<br/>';
}

Why would a script not like using MySQLi but is fine with MySQL?

I'm having some issues using mysqli to execute a script with SELECT,DELETE,INSERT and UPDATE querys. They work when using norm mysql such as mysql_connect but im getting strange results when using mysqli. It works fine with a lot of the SELECT querys in other scripts but when it comes to some admin stuff it messes up.
Its difficult to explain without attaching the whole script.
This is the function for modifying...
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $databaseUsername;
global $databasePassword;
global $databaseDebugMode;
$link = #mysql_connect($databaseServer,$databaseUsername,$databasePassword);
#mysql_select_db($databaseName,$link);
$result = mysql_query($sql,$link);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysql_error()."]";
}
$insertId = mysql_insert_id();
return mysql_affected_rows();
}
and heres what I changed it to for mysqli
function database_queryModify($sql,&$insertId)
{
global $databaseServer;
global $databaseName;
global $dbUser_feedadmin;
global $dbUser_feedadmin_pw;
global $databaseDebugMode;
$link = #mysqli_connect($databaseServer,$dbUser_feedadmin,$dbUser_feedadmin_pw,$databaseName);
$result = mysqli_query($link, $sql);
if (!$result && $databaseDebugMode)
{
print "[".$sql."][".mysqli_error()."]";
}
$insertId = mysqli_insert_id();
return mysqli_affected_rows();
}
Does that look right?
It isn't actually producing an error but its not functioning in the same way as when using mysql. any ideas?
Here is the way I normally use Mysqli
$mysqli = new mysqli($myServer, $myUser, $myPass, $myDB);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit;
}
$result = $mysqli->query($query);
while ($row=$result->fetch_assoc()) {
print_r($row);
}
Note: mysqli is a class, $mysqli is the variable that holds the instance of that class, query is a method of that class that returns a result class that has methods of its own.
You are running all statements at once as far as php is concerned, so functions like affected rows or last inserted id will not work as expected.
(Correct me if I'm wrong I haven't been using mysqli for a while.)
some of the mySqli functions needed some tinkering such as including $link

Categories