PostgreSql All returning results are "Array" - php

I have this piece of code
<?
$db = pg_connect("host=h port=p dbname=dbn user=usr password=pass");
if ($db) {
echo 'Connection attempt succeeded.' . '<br>' . '<br>';
}
else{
echo 'Connection attempt failed.' . '<br>' . '<br>';
}
$query = "SELECT column1 FROM table";
$result = pg_query($db, $query);
while ($row = pg_fetch_array($result)) echo $row. '<br>'. '<br>';
echo pg_dbname($db). '<br>' ;
echo pg_get_pid($db);
?>
The result should be three numeric values. When I run it, all I get are three strings "Array".
Connection attempt succeeded.
Array
Array
Array
dbname
pid
Can anyone help, please?

DO:
while ($row = pg_fetch_all($result)) echo $row['column1']. '<br>'. '<br>';
OR debug:
while ($row = pg_fetch_all($result)) var_dump($row) . '<br>'. '<br>';

Related

no data gets print where the query returns too many results

I have a query which is supposed to retrieve data from mysql and print it on the browser. It is working with a few rows of data but when the data gets bigger it just stops working and doesn't give any errors.
$result = mysql_query($query);
$json_array = array();
while($row = mysql_fetch_assoc($result)){
$json_array[] = $row;
}
print mysql_error();
print json_encode($json_array);
I have tried everything but nothing seems to work.
I'm very surprised it works at all.
This would work if $row was formatted.
Use foreach()
I doubt this would work either:
foreach($json_array as $row){
echo "$row<br>\n"
}
This should work (replace colx with the name of the table columns):
foreach($json_array as $row){
echo $row['col1'] . ', ' . $row['col2'] . ', ' . $row['col2'] . "<br>\n"
}
foreach($json_array as $row){
echo $row['name'] . ', ' . $row['address'] . ', ' . $row['phone'] . "<br>\n"
}
#Lessmore has right, maybe the PHP process has reached the memory limits in the server, try with less columns or registers, but I understand your need, then you need to write your self json_encode code to write row by row. Some like this:
$first = null;
header('Content-Type: application/json');
echo '[';
while ($row = mysql_fetch_assoc($result)) {
if ($first) {
echo ',';
}
echo json_encode($row);
!$first && $first = true;
}
echo ']';
exit;

Showing one row. Need to show it in a loop

I am trying to figure out how to use this in a loop. Any help will be appreciated.
$conn = mysql_connect("localhost", "some_user", "password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("some_db")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT favid FROM ajaxfavourites";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
}
mysql_free_result($result);
Currently it displays results as:
116677889922
I need them to show them as (the way they are displayed in DB):
1166
7788
9922
PS I am aware that this function is deprecated, I am just trying to fix one of my older sites.
choose One of these ways:
echo $row["favid"]."<br>";
echo $row["favid"]."\n";
echo $row["favid"].PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
echo "\r\n";
}
You can simply echo the value with '<br/>' or '<p>' like following:
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"] . '<br/>';
}
OR
while ($row = mysql_fetch_assoc($result)) {
echo '<p>' . $row["favid"] . '</p>';
}
Also you can just put all favid into array and then in another loop, can customize how to show them, like following:
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row["favid"];
}
foreach($ids AS $idv) {
echo '<p>' . $idv . '</p>';
}

my pdo connection doesn't work

Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';

printing out a json array

I am trying to figure out how to print a json array. I am trying to handle this from Android code but it is not working. I believe the problem lies in how I am outputting json. the below doesn't show anything. The script is below:
<?php
// Create connection
$conn=mysqli_connect("localhost","dhdkahd","dsdajdsa","dsadjsajd");
$json = array();
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!$conn->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $conn->error);
}
$sql='SELECT title, description, country, city, rate FROM discounts';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>
thanks in advance
You can only call json_encode once. You're double-encoding everything.
The line where you're adding data to the array needs to be
$json[] = $row;
Then, when the array is built up, you encode the entire thing in one single call:
echo json_encode($json);
You call json_encode twice. To fix it, change your code to:
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = $row;
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>

Printing result of mySQL query with INNER JOIN

I have a working SQL statement that returned correct results when I checked it on MAMP.
SELECT `questions`.`questionID` AS question, `questions`.`questionText`,
`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`
But I can't figure out how to print the output with php. Please help. This is the code:
<html>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect("localhost","root","root","Theory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print
echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
echo "}";
}
mysqli_close($con);
?>
</body>
</head>
I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.
You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!
replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.
EDIT to answer the question's comments:
when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.
Try this:
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questionID'] . "}"; //this is not the full print
echo "{" . $row['questionText'] . "}"; //just for checking
echo "}";
}
$sql is aparently not set. You can do:
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}

Categories