I'm trying to get data from a postgresql database, I get the error: pg_last_error() expects parameter 1 to be resource, object given in /path/to/query.php
So the data is as an object not a resource. Any ideas how to fix this?
The SQL works with this code:
foreach ($conn->query($sql1) as $row)
{
print $row["Site_ID"] . " ";
print $row["Site_name_1"] . "<br /> ";
}
But the problem arrises when I use pg_query instead.
Here's my code:
<?php include 'header.php'; ?>
<div class='container'>
<?php include 'menu.php'; ?>
<?php include 'PDO_connect.php'; ?>
<?php
$sql1='SELECT "Site_ID", "Site_name_1" FROM "Sites" ORDER BY "Sites"."Site_ID" ASC';
$result1 = pg_query($conn,$sql1);
if(!$result1) {
echo "There is an error!";
echo pg_last_error($conn);
}
?>
My connection info
<?php
try {
$dbuser = 'usr';
$dbpass = 'pwd';
$host = "localhost";
$dbname="db";
$conn = new PDO('pgsql:host=localhost;dbname=db', $dbuser, $dbpass);
}catch (PDOException $e) {
echo "Error : " . $e->getMessage() . "<br/>";
die();
}
?>
As said in the comments I was mixing PDO and pg_connect, this solves my problems:
<?php
$servername = "localhost";
$username = "usr";
$password = "pwd";
$database = "db";
?>
<?php
$conn = pg_connect("host=localhost dbname=$database user=$username password=$password")or die("Can't connect to database".pg_last_error());
?>
Related
I am trying to send a data from android studio, but I am getting lines under the table instead of assigning data.
Dont know where I am gone wrong.Plz help me.Thanks in advance.
This is my PHP code
add_employee
<?php
include('connection.php');
if (isset($_POST["name"])){
$emp_name = $_POST["name"];
echo $emp_name;
echo "is your name";
}
else{
$emp_name = NULL;
echo "POST filename is not assigned";
}
$success = 0;
$status = "Active";
$sqli = "INSERT INTO `employee` (`emp_name`) VALUES ('$emp_name')";
if(mysqli_query($conn,$sqli)){
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysqli_close($conn);
?>
Connection.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($conn,'student');
?>
You have so many errors in your code. no db name, no proper query definition. you can use this simple code:
Connection.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "slim";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Inserting employee code:
<?php
if (isset($_POST["name"])){
$emp_name=$_POST["name"];
echo $emp_name;
echo "is your name";
}
else{
$emp_name = null;
echo "POST filename is not assigned";
}
$success=0;
$status="Active";
$sql = "INSERT INTO employee (name)
VALUES ('$emp_name')";
if ($conn->query($sql) === TRUE) {
$success=1;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
It's working and easy to understand for you.
I want to make a dropdown list and i use this codes:
<div class="selector">
<?php
include ("connect.php");
$db = new mysqli('localhost', $dbuser, $dbpass, $dbnam);
?>
<div class="label">Select Name:</div>
<select name="names">
<option value = "">---Select---</option>
$stmt = $db->prepare("SELECT `name` FROM `monitoare`");
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch()){
echo "<option value='$name'></option>";
}
$stmt->close();
?>
</select>
as index.php
and this:
<?php
$dbname = 'mydabase';
$dbuser = 'myuser';
$dbpass = 'mypass';
?>
as connect.php and after i launch this the drop stays just with ---select--- as an option
I reckon that you should do all of this using either MySQLi procedural or object oriented rather trying to do with prepared statements.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
You can save this in a 'connect.php' file and include it in the relevant file.
The solution to getting dropdown instead of --select-- without any errors is shown below
echo "<select name='names'>"
$sql = "SELECT `name` FROM monitoare";
$result =mysqli_query($db, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row['name'].">".$row['name']."</option>";
}
} else {
echo "No results found";
}
?>
For further reference check out http://php.net/manual/en/book.mysqli.php and also https://www.w3schools.com/php/php_mysql_insert.asp
Here's a (corrected) example, adapt to your code :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$host = ""; /* your credentials here */
$user = ""; /* your credentials here */
$pwd = ""; /* your credentials here */
$db = ""; /* your credentials here */
/* connect to DBd */
$mysqli = mysqli_connect("$host", "$user", "$pwd", "$db");
if (mysqli_connect_errno()) { echo "Error connecting to DB : " . mysqli_connect_error($mysqli); }
$query = " SELECT `name` FROM `monitoare` ";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($name);
$stmt->store_result();
if ($stmt->num_rows > 0) { /* we have results */
echo"<select name=\"names\"><option value=\"\">---Select---</option>";
while($stmt->fetch()){
echo "<option value=\"$name\">$name</option>";
}
echo"</select>";
}
else
{ echo"[ no data ]"; }
?>
I am trying the fetch the data from my database sunypub from the table journal.
Out of many attributes, I am trying to get three atrributes which are of my use on the webpage through PHP, but it is not showing anything on the webpage.
This is the option which is directing to the page display.php, which will show me the attributes value of attribute jname, date and location from the table journal
<div align = "left">
<form action = "display.php">
<input type = "submit" value = "Show all the Conference List">
</form>
</div>
display.php:
<? php
// Create Local variable
$taken = "false";
$database = "sunypub";
$password = "";
$username = "root";
// Connect to database
$con = mysql_connect('localhost', $username, $password, $database) or die ("Unable to connect");
#mysql_select_db($database) or die("Database not found");
echo "Database Connected";
$query = "select * from journal ";
$result = mysql_query($con,$query) or die("Strange Error");
echo "Database Connected";
while( $row = mysql_fetch_assoc( $result, MYSQL_ASSOC ) ){
echo $row['jname'];
echo $row['date'];
echo $row['location'];
echo "Database Connected";
}
mysql_close($con);
?>
mysql_* is deprecated and is removed in new PHP version. So I highly recommend you to change to PDO or mysqli_* prepared statements, instead of fixing your old code.
So your code could look something like this:
(Note that you have to remove the space here: <? php)
<?php
// Create Local variable
$taken = "false";
$dbhost = "localhost";
$dbname = "sunypub";
$dbpass = "";
$dbuser = "root";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM journal";
foreach($dbh->query($sql) as $row) {
echo $row['jname'];
echo $row['date'];
echo $row['location'];
echo "Database Connected";
}
$dbh = NULL;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
How can I get this to echo or print out the results of a select statement via php?
<?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
<?php
$query="SELECT * FROM mydb.product";
$result=mysql_query($query);
echo "$result";
echo $result;
?>
I've gotten this far now, but it still returns nothing. Does the problem lie within my mysql table? Or does it fall somewhere else
<?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$sth = $db->prepare("SELECT * FROM mydb.test;");
$sth->execute();
$result = $sth->fetchAll();
?>
<h1> Im here</h1>
<?php
foreach ($result as $row) {
echo "<tr>";
echo "<td>{$row['name']}</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
?>
<h1> Im still here</h1>
Thanks for all the help
You need to look through the results. If there are, say, 3 columns in each row then your code would look something like this:
for($i=0;$i<mysql_num_rows($result);$i++) {
$row_array=mysql_fetch_row($result);
echo($row_array[0]." ".$row_array[1]." ".$row_array[2]."<br />");
}
As suggested in the comments, you'll have to loop through the fetched results:
$query="SELECT * FROM mydb.product";
$result=mysql_query($query);
// Add these lines:
while ($row = mysql_fetch_assoc($result)) {
var_dump($row);
// each item from the row could be used like this:
// echo $row['field'];
}
More information can be found here: http://php.net/manual/en/function.mysql-query.php
Please note that mysql_query is depricated, and you should consider switching to mysqli (http://php.net/manual/en/book.mysqli.php) or PDO (http://php.net/manual/en/ref.pdo-mysql.php)
As of recently ive been learning php and at that conjuntion in between where i have to now use Mysql in order to keep my bigger info table ogranized, well i wrote this code in order to show the tables (or so i think i did it right). im completely stumped because i can not see any of the displaying tables that i am calling on and the more ive tried the less i works so i was wondering if anyone can see a loop hole in my code or maybe im doing something wrong? or maybe everything ive done is wrong...?
`
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
?>
<?php
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<ul>
<?php
while($subject = mysqli_fetch_assoc($result)) {
?>
<li><?php echo $subject["menu_name"] . "(" . $subject["id"] . ")"; ?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result);
?>
</body>
</html>
<?php
mysqli_close($connection);
?>`
Have you forgotten the opening PHP tag at the beginning of your page?
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno () . ")"
);
}
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE visible = 1 ";
$query .= "ORDER BY position ASC";
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed");
}
?>
Two things i think could be wrong.
Here is a correct implementation to compare. It could be the first PHP opening tag, i also added the default port to the connect statement, and added some try catches with error messages, these can tell if the connect or query is not working.
<?php
$dbhost = "localhost";
$dbuser = "juliegri_AAlassa";
$dbpass = "********"; // to not show real password
$dbname = "juliegri_AAlassaly";
//original connect statement with a port added in
try {
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname , 3306);
} catch(Exception $e) { echo $e->getMessage(); }
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Query looks fine, easier to trouble shoot when its one line, first get it working then break it up
$query = "SELECT * FROM subjects WHERE visible = 1 ORDER BY position ASC";
// This will try to fetch the result and give an error if it can't.
try { $result = mysqli_query($connection, $query);
} catch(Exception $e) { echo $e->getMessage(); }
if (!$result) { die("Database query failed"); }
?>
Is it alright if I alter some of your codes?
See this:
<!doctype html>
<html lang="en">
<head>
<title>databases</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION */
$connection=mysqli_connect("localhost","juliegri_AAlassa","YourPassword","juliegri_Aalassaly");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* START QUERY */
$result=mysqli_query($connection,"SELECT * FROM subjects WHERE visible='1' ORDER BY position ASC");
?>
<ul>
<?php
/* DO THE WHILE LOOP */
while($subject = mysqli_fetch_array($result)) {
?>
<li><?php echo $subject['menu_name'] . "(" . $subject['id'] . ")"; ?></li>
<?php
} /* END OF WHILE LOOP */
?>
</ul>
</body>
</html>