Established connection to database but rendering a blank page - php

I am simply trying to display data from a table in my database.
For some reason, it keeps rendering a blank page.
I have no training at all. SO I am sure my code looks like crap. But I can usually get it to work. I researched but all I could find were connection problems. I get a 'connected successfully' message but no data and no error message.
<?php
$db_host = 'localhost';
$db_user = 'user';
$db_pass = '';
$db_name = '';
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$query = "SELECT * FROM `my_table`";
$result = mysql_query("SHOW COLUMNS FROM `my_table`");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
mssql_field_name($result,0);
// print_r($row);
}
}
?>

$db_name = ' ' ; is Null write Your Database Name

You should first provide a $db_name, because it's currently blank

$db_pass = '';
you need to provide your database name in here, else your application is literally trying to connect to nothing

You might have to check $mysqli_connect, that the $db_name=''; is null...put your database name inside ''

try like this.
<?php
$conn=mysqli_connect('localhost','root',' ','databasename');
$query="Select * from my_table";
$result = mysqli_query($conn,$query);?>
<table>
<tr>
<th>name</th>
<th>full_name</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td><?php echo $row["name"]; ?></td>
<td><?php echo $row["full_name"]; ?></td>
</tr>
<?php
}
?>

Please add your database name and database password, then you can try like this :
$sql = "Select * from table_name";
if ($result=mysqli_query($conn,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
$response[] = $row;
}
} else {
echo 'Could not run query: ' . mysqli_error();
exit;
}
print_r($response);

Related

Trying to echo out every name in database table inside hrml list

I have been trying to echo out database data through a while loop now for awhile but it doesn't work, I can't find where the issue is. I have tried echoing out data manually and that works just fine.
<?php $results = mysqli_query($con,"SELECT * FROM guestbook ORDER BY id DESC"); ?>
<?php while ($row = mysqli_fetch_assoc($results)) : ?>
<li>
<?php echo $row['message']; ?>
</li>
<?php endwhile ?>
First of all make sure you are connected to the database. I don't know if you omitted that on purpose or not. Also, check if the connection is established.
<?php
//Insert your server info here
$servername = "servername";
$username = "root";
$password = "root";
$dbname = "test_database";
// Create and check your connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM guestbook ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>' . row["message"] . '</li>';
}
} else {
// Your query produced 0 results
echo "Empty result!";
}
// Remember to close the connection
mysqli_close($conn);
?>

Retrieving data from MySQL database

Not sure what I'm doing here.
The following code outputs the Database connected statement, but is not displaying any records ("0 results"):
<?php
//Server Details
$host ="localhost";
$user = "X32284679";
$password = "X32284679";
//Connection
$dbc = mysql_pconnect($host,$user,$password);
//Database Selection
$dbname="X32284679";
mysql_select_db($dbname);
if (!$dbc)
{
die("Connection Failed: " .mysqli_connect_error());
}
echo "Connected";
$sql = "select * from staff";
$result = $dbc -> query($sql);
if ($result ->num_rows >0 )
{
echo"<table><tr><th>Email</th><th>Name</th><th>Mobile</th> <th>Address</th><th>Password</th></tr>";
while($row = $result-> fetch_assoc())
{
echo "<tr><td>" .$row["staff_email"]."</td><td>".$row["staff_name"]."</td><td>".$row["staff_mobile"]."</td><td>".$row["staff_address"]."</td><td>".$row["staff_password"]."</td></tr>";
}
echo "</table>";
}
else
{
echo "0 Results";
}
$dbc->close();
?>
this looks like a whole lot of copy & paste from tutorials.
The use of both mysql_ and mysqli_ functions is pretty much useless all together..
As it look slike you want it in mysql_ ive re written your code to fit your needs.
Code:
<?php
//Server Details
$host ="localhost";
$user = "X32284679";
$password = "X32284679";
//Connection
mysql_connect($host,$user,$password) or die("An error occured while connecting...");
//Database Selection
$dbname="X32284679";
mysql_select_db($dbname);
$sql = "select * from staff";
$Query = mysql_query($sql);
if (mysql_num_rows($Query)){
$html .= "<table><tr><th>Email</th><th>Name</th><th>Mobile</th> <th>Address</th><th>Password</th></tr>";
while($row = mysql_fetch_array($Query)){
$html .= "<tr><td>" .$row["staff_email"]."</td><td>".$row["staff_name"]."</td><td>".$row["staff_mobile"]."</td><td>".$row["staff_address"]."</td><td>".$row["staff_password"]."</td></tr>";
}
$html .= "</table>";
}
else{
$html .= "0 Results";
}
echo $html;
mysql_close();
?>

php 'no database selected' but it is connected to the database

I have checked other questions with the same title but can't fix this. I have connected to the database though because the login works and I can display the user's username. Here is the relevent code, the second part is what's causing the error, thanks:
<?php require 'connection.php' ?>
<?php
session_start();
?>
<content>
<?php
//Select all from the categories table and order by the category title in ascending order (ASC)
$sql = "SELECT * FROM categories ORDER BY category_title ASC";
//$res = the result of the above query or die if error
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) > 0) {
} else {
"<p>No categories availible</p>";
}
?>
</content>
Here is an example, for the visual of it.
<?php
$dbname = 'so_gibberish';
$dbuser = 'GuySmiley';
$dbpass = 'MyPassword';
$dbhost = 'localhost';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$test_query = "SHOW TABLES FROM $dbname";
$result = mysql_query($test_query);
...
...
mysql_close($link);
However, go with PDO
It is less sickly, full of robustness, and safer to say the least for binding:
Again, just a visual.
<?php
$theNum=102; // get from user, this is hard-coded
try {
$dbh = new PDO('mysql:host=localhost;dbname=so_gibberish;charset=utf8', 'GuySmiley', 'MyPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare('SELECT id,smin,smax from ranges7
WHERE smin <= :theNum AND smax >= :theNum');
$stmt->bindParam(':theNum', $theNum, PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// one row we hope
$data = "id: ".$row['id'] . ", smin: " . $row['smin'] . ", smax: " . $row['smax'] . "\n";
print $data;
}
$stmt = null;
// PDO closes connection at end of script
} catch (PDOException $e) {
echo 'PDO Exception: ' . $e->getMessage();
exit();
}
?>

How to delete a record from mysql using a button?

I would like to be able to delete a row using the delete-button I display at the end of each row. I need two queries to delete a person from my database completely since I have a n-m relationship between Persons and Functions.
The queries are as follows:
delete from `Persons` where `Person ID` = '1';
I would like to implement these queries using the delete-button provided in the actual code, how can I do this?
UPDATE:
I made changes according to what Kristian Hareland wrote, and it reloads but the person isn't deleted, what should be changed to make it work?
showall.php:
<table>
<thead>
<tr>
<?php
// Variables
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$query = "SELECT p.`Person ID`, p.`First Name`, p.`Last Name`, p.Gender, p.`Date Of Birth`, p.Email, p.`Phone Number`, c.Region, c.Country, p.`Delegation ID`
FROM Persons as p, Chapters as c
WHERE c.`Chapter ID`=p.`Chapter ID`
ORDER BY p.`Delegation ID";
$result = mysql_query($query) or die($dberror3 . mysql_error());
$row = mysql_fetch_assoc($result);
foreach ($row as $col => $value) {
echo "<th>";
echo $col;
echo "</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
DeletePerson.php:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "CISV";
$dberror1 = "Could not connect to database: ";
$dberror2 = "Could not select database: ";
$dberror3 = "Could not execute query: ";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ($dberror1 . mysql_error());
$select_db = mysql_select_db('CISV') or die ($dberror2 . mysql_error());
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
$Del = mysql_query("DELETE FROM `Persons` WHERE `Person ID` = '$UserId'");
if($Del){
$Flag = TRUE;
}
else{
$Flag = FALSE;
}
header("Location: /showall.php?delete=$Flag");
}
else{
die("Error");
}
I would use JavaScript and Ajax here.
Make a Html-button with an onclick function like delete_user();
delete_user() calls a .php file to validate the rights and execute some mysql-delete promts.
The .php file returns a boolean to the JavaScript.
You could catch that boolean up and inform the user about the result.
IMHO best way is create separate file functions.php
<?php
//functions.php
$id = filter_this($_POST[id]);
mysql_query("delete from Persons_Functions where `Person ID` = '$id');
?>
and send there via JQuery:
function deleteuser(id){
$.post("admin_action.php", {action:'delete_user',id:id}, function(data){
if(data.trim()=="done"){
console.log("OK!");
});
}}
Without JS You can use HTML (just change BUTTON to A):
<a href='script.php?action=delete&id=12'>DELETE</a>
and PHP:
$id = $_GET[id];//filter this value
mysqli_query($link, "DELETE FROM users WHERE ID='$id'"); //use mysqli
I would use the GET method for this
<?php foreach ($results as $result): ?>
Delete
<?php endforeach; ?>
At the top of index.php
if (isset($_GET['action']) && $_GET['action'] == 'delete') {
if (isset($_GET['id']) && intval($_GET['id']) != 0) {
$id = intval($_GET['id']);
$stmt = "delete from table where id='{$id}'";
}
}
Just use a link:
<tbody>
<?php
mysql_data_seek($result, 0);
while ($row = mysql_fetch_assoc($result)) {
?>
<tr>
<?php
foreach($row as $key => $value){
echo "<td>";
echo $value;
echo "</td>";
}
?>
<td>Delete</td>
</tr>
<?php } ?>
</tbody>
DeletePerson.php:
<?php
$UserId = mysql_real_escape_string($_GET['id']);
if(isset($UserId)){
//DELETE QUERY
mysql_query("DELETE FROM Persons WHERE Person ID = '$UserId'");
mysql_query("DELETE FROM Persons_Functions WHERE Person ID = '$UserId'");
header("Location: /showall.php?flag=deleted");
}
else{
die("Error");
}

mysql_query how to display html for if condition

So I have this rustic and basic php that will check a value in my database and if its corrects it will pull out the rest of that row I guess but my problem is how to echo certaine html if the result is okay and how to echo some other html if else.
btw atm else is not working, in other words if you input a code that is not on my db it will not show anything
<?php
$db_hostname = 'localhost';
$db_database = 'codedb';
$db_username = 'root';
$db_password = '';
$table = 'users';
$field = 'code';
$test = 'first_name';
// Connect to server.
$connection = mysql_connect($db_hostname, $db_username, $db_password) OR DIE ("Unable to
connect to database! Please try again later.");
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
echo "Hello: $name $test";
}
}
else {
echo "Im sorry you buddy, you are not a winner this time! $test";
}
mysql_close($connection);
?>
You can use mysql_num_rows(), it's the best way.
if( mysql_num_rows($result) > 0 ){
/* Anything you want here on success */
} else {
/* Anything you want here on failure */
}
if(mysql_num_rows($result) > 0) { echo "output"; } else { echo "error msg"; }
Use mysql_num_rows against the query.
if(mysql_num_rows($result)){ } else { }
Instead of echoing every html value you can simply enclose html in if statements
like:
<?php
$query = "SELECT * FROM $table WHERE $field = '{$_GET["qcode"]}'";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["$field"];
$test = $row["$test"];
?>
<b>Hello: <?php echo $name $test"; ?></b>
<?php
}
}
else {
?>
<b> Im sorry you buddy, you are not a winner this time! </b> <?php echo $test";
}
mysql_close($connection);
?>
First you have to correct syntax of database selection like this
mysql_select_db($db_database,$connection);
Insted of
mysql_select_db($db_database);
Check Manual

Categories