----- UPDATED
Code works when I'm running it from my schools public_html folder. However, when I create the exact same file, upload to my personal web server it does not work and only produces a blank screen. Not exactly sure what this means, maybe that I don't have permissions?
Updated Code to reflect suggestions (still not working)
-----------
Hi I'm a student learning to use php and postgres. Currently I'm just trying to open a connection from my hosted website to my database on my school's server. I'm getting a blank result with my following php file.
I put 'xxxxx' as the connection fields in order not to give away my username and password - the real file has the correct information.
My question is... is there anything wrong with this php file?
<html>
<body>
<h1>Test</h1>
<?php
$username = "xxxxx"
$password = "xxxxx";
$databasename = "xxxxx";
$hostname = "xxxxx";
$connection = pg_connect("host=$hostname dbname=$databasename user=$username password=$password") or die ("could not connect");
$query = "SELECT unit_name from units";
$result = pg_query($connection, $query) or die("ERROR: " . pg_last_error());
$row = 0;
while ($row = pg_fetch_row($result)) {
echo "$row[0]<br>\n"
};
pg_close($connection);
?>
</body>
</html>
You have to use pg_fetch_row
Try this
$query = "SELECT unit_name from units";
$result = pg_query($connection, $query) or die("ERROR: ".pg_last_error());
if(!result)
{
echo "An error occurred.\n";
exit;
}
$data = [];
while ($row = pg_fetch_row($result)) {
$data[] = $row;
}
foreach($data as $value)
{
echo $value;
}
This Code success on my side! try this.
$link = mysqli_connect("YourHostname", "Your Username", "YourPassword", "YourDBName");
// Check conn
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql="/*Your SQL CODE HERE*/";
if(mysqli_query($link, $sql)){
echo "Success!";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
Related
I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL. I am using the following PHP script.
I have the following objectives:
Connect to the existing database. This part works well.
Get data from the column 'Brand' of the table 'Transport' in $sql. This part is not working at this stage. echo ($sql) returns SELECT Brand FROM Transport WHERE Type = 'car'
Could you please let me know if you see the solution to this issue and if the remaining part of the code is correct. This is my f_sqlConnect()
function f_sqlConnect() {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: '.mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can not use'.DB_NAME.
': '.mysql_error());
}
}
/*This function cleans up the array to protect against injection attacks */
function f_clean($array) {
return array_map('mysql_real_escape_string', $array);
}
<?php
// Create connection
$link = f_sqlConnect();
// Getting data from the column Brand of the table Transport
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"]. "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>
Here is the code, without seeing your f_sqlConnect(); mothod. This method should return connection string for DB in your case. But you can use following code this must work.
<?php
$servername = "Your_db_host";
$username = "your_db_username";
$password = "your_db_password";
$dbname = "your_DB_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Brand FROM Transport WHERE Type = 'car'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Brand: " . $row["Brand"];
}
} else {
echo "0 results";
}
$conn->close();
?>
NOTE: Object oriented way of mysqli, You can use procedural way too to connect and get data.
I'm a newbie at PHP. I'm simply trying to access my database and here is the code. I'm using the object oriented style for accessing the database.
It says "Trying to get property of non-object on line 25".
What am I missing?
<?php
$servername = "localhost";
//$username = "";
//$password = "";
$database = "MyPetProject";
$conn = new mysqli ($servername, $database);
if ($conn-> connect_error)
{
die ("Connection failed : " . $conn->connect_error);
}
else
{
echo "Connection Successfull";
}
$sql = "SELECT * FROM User";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while( $row = $result->fetch_assoc())
{
echo $row["Sr.no"] . " " . $row["Name"] . " " . $row["Online"];
}
}
else
{
echo "0 results";
}
echo ("hello world");
$conn->close();
?>
Edit the following:
while( $row = $result->fetch_assoc($result))
And it should work
Answering my own question here.
I had commented $username and $password.
These are mandatory parameters for mysqli. The rest of the code is perfectly fine.
You should need a username and password for accessing mysql databases .
$mysqli = new mysqli("localhost", "user", "password", "database");
which is the second and third parameters respectively.
You could find all related documentation in this link.
http://php.net/manual/en/mysqli.quickstart.connections.php
I am trying a connection to mysql and retrieve some information. The connection is successful, but produces a blank page. Below is the code. Appreciate help in checking what is wrong.
Thank you in advance
Richard
<html>
<body>
<?php
// include server parameters
require('includes/configure.php');
$con=mysqli_connect(DB_SERVER,DB_SERVER_USERNAME,DB_SERVER_PASSWORD,DB_DATABASE);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//$username = $_GET['username'];
//$password = $_GET['password'];
$result = mysqli_query($con,"SELECT * FROM Workshops");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
</body>
</html>
Before $row = mysqli_fetch_array($result);
add this lines to 'what you get from DB'
echo "<pre>".var_dump($result)."</pre>";
Looks like mysqli_fetch_array has two categories i.e. numeric and associative array. Take a look at the example in the link. You can change your code as shown below.
http://www.w3schools.com/php/func_mysqli_fetch_array.asp
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["yourtablecolumn"],$row["yourtablecolumn"]);
You can also use, mysqli_fetch_assoc($result).
$row = mysqli_fetch_assoc($result)
<?php
$connection = new mysqli ("localhost", "root", "root", "register"); //1. You have to change here
if ($connection -> connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$select_db = mysqli_select_db($connection, 'register'); //2. you have to change Database name
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
$query = "SELECT * FROM `Workshops`";
$result = mysqli_query($connection, $query)
or die(mysql_error());
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
?>
Check with this code again rewrote & tested
Note : I have marked the places where you should change according to your database configurations
Open for any modifications
This should be in comment but I don't have enough reputation to comment, so I just post as answer.
You can try these checking:
Make sure your table name is correct
Instead of $data = $row[0], try $data = $row['your_columm_name']. If you only want a single record, edit your query by adding WHERE clause.
Hope these help, good luck.
On my website, a user's background URL is stored with their data in a database. I need to get this value and store it in a variable.
However, I am having trouble doing so, the code I have right now gives me an error but doesnt tell me what the error is.
My code:
<?php
error_reporting(E_ALL);
include 'config.php';
$pin = $_COOKIE["UID"];
// Create connection
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
if ($conn->query($query) === TRUE) {
$bg_url = $row[bg_url];
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;
mysqli_close($conn);
?>
$query = "SELECT * from users where pin ='$pin'";
$result = $conn->query($query);
Actually yes, the John's answer is correct, you're not using the return values properly, but you are neither accesing the variables properly, for example, I don't see where $row comes from. Try this and change it for array mode if you need to. I'm not very used to mysqli_* API, because I use PDO mostly.
if ($result) {
while($row = $result->fetch_object()) {
$bg_url = $row->bg_url;
}
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
echo $bg_url;
I make a random quote app, in which by pressing a button, i can load one random phrase. I created for this a MySQL database, and two php code.
I upload my two code in a web hosting, and the app is running!
But sometime it gives me "null" instead of the phrase. I don't know why.
I'm not very good with this.
What is probably the problem?
This is my index.php
require_once 'db.php';
$query = "SELECT * FROM quotes ORDER BY rand() LIMIT 1";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result)) {
print(json_encode($row['quote']));
}
And this is my db.php
// Create connection
$con=mysqli_connect("host","user","pass","a6361246_phrases");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
You can use the first three lines in your db.php file like this...
<?php
$host = 'localhost'; $db = 'database-name'; $user = 'database-user'; $pw = 'database-password';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
Don't forget to change database-name, database-user & database-password to your specific credentials.
Then using PDO get your phrase like this...
<?php
require_once 'db.php';
try {
$sql = "SELECT * FROM Quotes ORDER BY rand() LIMIT 1";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
?>