I'm trying to echo data from DB using MySql and php - php

I'm trying to echo data from DB but it is showing 500 error. Same code works in some other server but it is not working in my present diff server.
<?php
error_reporting(0);
session_start();
$hostname_dbConn = "localhost";
$database_dbConn = "data_data";
$username_dbConn = "user_data";
$password_dbConn = "datauser";
$dbConn = mysql_pconnect($hostname_dbConn, $username_dbConn, $password_dbConn) or trigger_error(mysql_error(),E_USER_ERROR); mysql_select_db($database_dbConn, $dbConn);
$query_getconfig = "SELECT * FROM configuration WHERE status = 'A'";
$getconfig = mysql_query($query_getconfig, $dbConn) or die(mysql_error());
$row_getconfig = mysql_fetch_assoc($getconfig); $totalRows_getconfig = mysql_num_rows($getconfig);
?>

Remove error_reporting(0); and check what errors exactly are you facing?
Either #mysql_pconnect($hostname_explorecalirfornia, $username_explorecalirfornia, $password_explorecalirfornia) or trigger_error(mysql_error(),E_USER_ERROR); //# infront of mysql_pconnect or use below written code
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DBNAME);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
For fetch record.
$sql= "SELECT * FROM configuration WHERE status = 'A'";
// get the result object.
$result = $mysqli->query($sql);
// fetch the result row.
$data = $result->fetch_assoc();
return $data;
with mysqli
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);

Related

SQLi Error when trying to echo a certain ID in PHP

I am making a status update page for practicing PHP and MySQL.
I am currently trying to echo the saved status on the page.
The statuses are saved in a row called "Status" and they are all given a certain ID in a row called "statusID."
The problem I am having is which fetch I want to use because converting it into a string using (string)$var doesn't work. ($var is an example).
Also, the $idNum variable is something for later use, shouldn't have anything to do with this.
Here is the code: (Obviously the first variables are censored so none tries to connect to the database, the connection working in the actual code.)
The problem lies in the $fetchRes I believe.
<?php
$idNum = 1;
$servername = "censored";
$username = "censored";
$password = "censored";
$db_name = "censored";
$conn = mysqli_connect($servername, $username, $password, $db_name);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Status FROM SavedStatuses WHERE statusID=1;";
$statusQuery = mysqli_query($conn, $sql);
$fetchRes = mysqli_fetch_assoc($statusQuery);
if($conn->query($sql) == TRUE)
{
echo $fetchRes;
} else {
echo "Failed to retrieve status, error: " . $conn->error;
}
?>
As I mentioned in comments, you are querying twice and not looping over (successful) results.
A "loop" is to use either a while or a foreach. I used a while loop for this example.
From the "official" manual:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
Example:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
So in your case, your code would read as:
Sidenote: Status and status are two different animals, so make sure the letter case matches (in the loop).
<?php
$mysqli = new mysqli("censored", "censored", "censored", "censored");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT Status FROM SavedStatuses WHERE statusID=1";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row["Status"];
}
/* free result set */
$result->free();
}else{
echo "The query failed: " . mysqli_error($mysqli);
}
/* close connection */
$mysqli->close();
?>

Select SQL query is not working in PHP

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.

php results return empty

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.

php query to database returning blank results

----- 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);

How to fetch assoc array while using mysqli prepare

To make sure my database is secure I'm using prepare statements. Here is my code:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
Now I want to know how can I use ASSOC fetch array
$embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC);
I want this so that I can just put something like below to get values
$embInfo['name']
and
$embInfo['email']
try this:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
while($embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
echo 'My name is '.$embInfo['name'].'and my email is '.$embInfo['email'].'<br/>';
}
mysqli_stmt_close($stmt);
May i suggest an alternative
{
$server = '';
$user = '';
$pass = '';
$db = '';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
$club=$_POST'club'];
$sql = "SELECT * FROM players WHERE club = '$club'";
$result=mysqli_query($mysqli,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['player'];
}
}

Categories