Unable to Retrieve data from the postgress database using Php? - php

I have created a Php file, which fetches the data from the Postgres Database, but when I run the file it doesn't displays the contents (records) which are present in the database table.
I ran this using both Apache server and Python SimpleHTTPServer also.
I restarted the Postgres server too.
Below is the code of that file:
index.php
<!DOCTYPE html>
<html>
<head>
<title>
webpage
</title>
</head>
<body>
<h1>
INFORMATION OF DATABASE
</h1>
<?php
$host = "localhost";
$user = "myappuser";
$pass = "password";
$db = "myapp";
echo "\n test";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM app1_snippet";
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_assoc($rs)) {
echo $row['id'] . " " . $row['name'] . " " . $row['phone_no']. " " . $row['status'];
echo "\n";
}
pg_close($con);
?>
</body>
</html>

Ya figured out how to do.
below is the Code.
<!DOCTYPE html>
<html>
<head>WELCOME</head>
<body style="background-color:#E4E5E7">
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
table#t01 {
width: 100%;
background-color: #f1f1c1;
}
</style>
</head>
<body>
<?php
$url= 'http://yoururltypehere.com';
$options = array(
'http' => array(
'header' => array(
'name: '.$_GET['name'],
),
'method' => 'GET',
),
);
$context = stream_context_create($options);
$output = file_get_contents($url, false,$context);
$arr = json_decode($output,true);
?>
<table style="width:100%">
<tr>
<th>ID</th>
<th>NAME</th>
<th>PHONE_NO</th>
<th>STATUS</th>
</tr>
<br>
<?php
for($x=0;$x<count($arr);$x++)
{
?>
<tr>
<td><?php echo $arr[$x]['id']; ?>
<td><?php echo $arr[$x]['name']; ?>
<td><?php echo $arr[$x]['ph_no']; ?>
<td><?php echo $arr[$x]['stats']; ?>
</tr>
<?php
}
?>
<br>
</table>
</body>
</html>

Related

how to add ajax to a php file

how could i add ajax to my php file ,that when i delete an item of the list the data should automatically reload and my list should be updated to the new list?
I made list of all my data with a button of delete
here is my code for php
<?php
function tableV1 ($row) {
echo '<tr>';
echo '<td>' .$row['id']. '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['lastname'] . '</td>';
}
$dbPassword = "micr2001";
$dbUserName = "PHPFundamentals";
$dbServer = "localhost";
$dbName = "PHPfundamentals";
// Create connection
$conn = mysqli_connect($dbServer , $dbUserName , $dbPassword,$dbName) or die("unable to connect to host");
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<style type="text/css">
table {font-size: 27px; }
tbody {}
td {border-bottom: 1px solid bisque;padding:15px;}
th {border-bottom: 1px solid bisque;padding:15px;}
thead {}
tr {}
</style>
</head>
<body>
<center>
<table>
<thead>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Action</th>
<th> </th>
</thead>
<?php
// Takes all the results from the table with genre 5.
$sql = "SELECT id,firstname, lastname FROM persons";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
tableV1($row);
$rowId = $row['id'];
$first_name = $row['firstname'];
$last_name = $row['lastname'];
echo '<td>'
. ' <a class="edit_btn btn" href=edit.php?id='.$rowId.'&lname='.$last_name.'&fname='.$first_name. '>Edit</a>'
. ' </td>';
echo '<td><a class="del_btn btn" href=delete.php?id='.$rowId.'>Delete</a></td>';
echo' </tr>';
}
} else {
echo '<tr><td colspan="3">0 results</td></tr>';
}
?>
</table>
</center>
</body>
</html>
<?php
$conn->close();
?>
here is the code for delete.php
<?php
require 'connection.php';
$id = $_GET['id'];
$sql = "DELETE FROM persons WHERE id = ".$id ;
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
mysqli_close($conn);
?>
i want the item that i delete should get off my list
Why do you even need AJAX? As user clicks Delete, she / he is redirected to the delete.php script. In that script after sucessful deletion you should just redirect the user back to the listing. This can be achieved by HTTP redirect (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection). Keep it simple!

Can someone explain why my MySQL table data is not being displayed?

I'm new to PHP and MySQL. I have an HTML table and form that submits the entered data to MySQL, but doesn't display the MySQL data in my HTML table. Here is an image for reference: https://i.imgur.com/OEDd6Px.png. I want the submitted data to display upon submission if possible but am unable to find a solution. Thanks in advance.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
if(isset($_POST["asin"]))
{
$asin = $_POST["asin"];
$category = $_POST["category"];
$submit = "INSERT INTO `user_input`(`id`, `asin`, `category`, `date`) VALUES (NULL, '$asin', '$category', CURRENT_DATE())";
$sql = mysqli_query($conn, $submit);
if (!$sql) {
die ('SQL Error: ' . mysqli_error($conn));
}
$display = "SELECT * FROM user_input";
$result = mysqli_query($conn, $display);
if (!$result) {
die ('SQL Error: ' . mysqli_error($conn));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>testEnv</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<style>
form {
padding-bottom: 10px;
padding-top: 10px;
}
table, thead, tbody, th, td {
padding: 4px;
border-collapse: collapse;
border: 1px solid black;
}
form {
font-size: 13px;
}
th, td {
width: auto;
text-align: center;
font-size: 13px;
}
</style>
</head>
<body>
<div class="container-fluid">
<form id="form" method="post">
<div>
<label id="asinLabel" for="asin">ASIN:</label>
<input id="asinInput" type="text" name="asin"></input>
<label id="categoryLabel" for="category">Category:</label>
<input id="categoryInput" type="text" name="category"></input>
<input id="submit" type="submit" value="Submit"></input>
</div>
</form>
</div>
<div class="container-fluid">
<table class="container-fluid">
<thead>
<tr>
<th>ID</th>
<th>ASIN</th>
<th>Category</th>
<th>Date</th>
<th>6:00 AM</th>
<th>8:00 AM</th>
<th>10:00 AM</th>
<th>12:00 PM</th>
</tr>
</thead>
<tbody id="tableBody">
<?php
while($row = mysqli_fetch_array($result));
{
echo '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['asin'].'</td>
<td>'.$row['category'].'</td>
<td>'. date('m d, Y', strtotime($row['date'])) .'</td>
<td>'.$row['6am'].'</td>
<td>'.$row['8am'].'</td>
<td>'.$row['10am'].'</td>
<td>'.$row['12pm'].'</td>
</tr>';
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script rel="script" type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script rel="script" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.js"></script>
<script rel="script" type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.js"></script>
</body>
</html>
Try to write
$display = "SELECT * FROM user_input";
$result = mysqli_query($conn, $display);
if (!$result) {
die ('SQL Error: ' . mysqli_error($conn));
}
block out side of the condition.

How to use the value of a link in search query

Could someone please help me how to do this?
When I click a link, it will be directed to a new page containing the contents related to the value of the link. Like for example, after clicking the title of an article, it will be directed to a new page containing its content. So the value of the link will be used in search.
search.php
<?php
if(isset ($_POST['valueTosearch']))
{
$valueToSearch = $_POST['valueToSearch'];
$query = "SELECT * FROM `events` WHERE CONCAT(`title`) LIKE
'%".$valueToSearch ."%'";
$search_result = filterTable($query);
}
else {
$query="SELECT * FROM `events`";
$search_result = filterTable($query);
}
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "silangagri");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP HTML TABLE DATA SEARCH</title>
<style>
table,tr,th,td
{
border: 1px solid black ;
}
</style>
</head>
<body>
<table style="padding-right: 2; padding-left: 2; padding-top: 4; padding-
bottom: :4">
<tr>
<th>title</th>
<th>location</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><?php echo $row['title']; ?></td>
<td><?php echo $row['location']; ?></td>
</tr>
<?php endwhile;?>
</table>
</body>
</html>
index.php
<?php
$host = "localhost";
$username="root";
$password="";
$database="silangagri";
$connect = new
PDO("mysql:host=$host;dbname=$database",$username,$password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM news ORDER BY date DESC";
$data = $connect->query($query);
?>
<!DOCTYPE html>
<html>
<body>
<form action = "search.php" method="post">
<?php foreach($data as $row) {
echo '<a name="valueTosearch" href="search.php">
<h5>'.$row["title"].'</h5></a>';
echo '<br><br>';?>
<?php
}
?>
</form>
</body>
</html>

How to output data using php from mysql database

I am making a blog using mysql to input and output data(blog posts) using php. I have create a table, inserted rows for the data such as: id, title, content and date in "addentry.php".
I am having problems outputting the data using php on my "viewblog.php". Where it says "//output from table"(line 115), thats where i want to output the data. Ive tried my best to find a solution.
Thanks in advance.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- image.html
A trivial document
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head><title> My Blog </title></head>
<style type ="text/css">
body{
position: fixed;
overflow:overlay;
width: 100%;
top: -20px;
left: -20px;
right: -40px;
bottom: -40px;
height: auto;
background-image:url(image.jpg);
background-size: cover;
}
.container{
background-color: #ecdad6;
padding: 30px;
width:920px;
margin-left: 25%;
padding-bottom:1000px;
padding-left:0px;
border: 2px solid black;
}
.links{
position: absolute;
padding-right: 135px;
padding-bottom: 800px;
margin-left: 680px;
margin-right: 100px;
font-size: 20px;
word-wrap: break-word;
top:-3px;
}
.blog{
position: absolute;
width:678px;
padding-bottom: 920px;
margin-left: 10px;
font-size: 20px;
text-align: left;
word-wrap: break-word;
}
ul li { margin-top: -10px; }
}
iframe{
border:2px solid black;
width:4000px;
display:block;
*}
}
</style>
<body>
<!--Logo & hyperlinked -->
<p align = "center"><img src = "Logo.jpg" alt="My logo" width="10%" height="10%"/></p>
<br/>
<hr width="50%">
<div class="container">
<div class="blog">
<?php
$host = "dbprojects.eecs.qmul.ac.uk" ;
$user = "hm315" ;
$pass = "cXtXuyf2pnF4H" ;
$db = "hm315" ;
$link = mysql_connect ( $host , $user , $pass );
if (! $link ) {
die( 'Could not connect: ' . mysql_error ());
}
echo 'Connected successfully' ;
$db_selected = mysql_select_db ( $db , $link );
if (! $db_selected ) {
die ( 'Can\'t use $db : ' . mysql_error ());
}
echo 'Connected successfully' ;
//select from table
$sql = "SELECT * FROM post02";
$row=mysql_fetch_array($sql);
echo 'selecting table works';
//output from table
//connection + database, record created and close connection.
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
mysql_close ( $link );
?>
<form action='index.php' method='get'></form>
<div class="links">
<ul><li>home</li></ul>
<ul><li>logIn</li></ul>
<ul><li>add_entry</li></ul>
</div>
</div>
</div>
</body>
</html>
<?php
$host = "xxx.ac.uk" ;
$user = "xxx" ;
$pass = "xxx" ;
$db = "xxx" ;
$link = mysql_connect ( $host , $user , $pass, $db );
if (! $link ) {
die( 'Could not connect: ' . mysql_error ());
}
echo 'Connected successfully' ;
$db_selected = mysql_select_db ( $db , $link );
if (! $db_selected ) {
die ( 'Can\'t use $db : ' . mysql_error ());
}
/*
// create a table
$sql="create table post02(id INT(6) unsigned auto_increment primary key , title varchar(30) not null, content varchar(255) not null, date TIMESTAMP)";
$connection = mysql_query($sql);
if (! $connection ) {
die ( 'Cant create table : ' . mysql_error ());
}
echo 'Created a table successfuly' ;
*/
//insert to table
echo'insert table - initializing';
if($_POST['submit']){
$title = $_POST['title'];
$content = $_POST['content'];
$date = date('l jS \of F Y h:i:s A');
}
$sql = "INSERT INTO post2('title', 'content', 'date') VALUES ($title, $content,$date))";
if($title =="" || $content=="" ){
echo "please compelete your post!";
return;
}
echo'insert table completed';
mysql_query($db ,$sql);
header("location: viewblog.php");
//record created is successful
if ($link->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $link->error;
}
mysql_close ( $link );
?>
The question was not that clear, I wrote a sample code according to the question's title. Oh, and don't forget to change your creds.
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<?php
$r = $link->query("SELECT * FROM table");
while($rf = $r->fetch_assoc())
{
echo "<tr>
<td>{$rf['column_1']}</td>
<td>{$rf['column_2']}</td>
<td>{$rf['column_2']}</td>
</tr>";
}
?>
</table>

Select data from SQL database and display in table does not work

I don't understand why this isn't working, I have been stuck on this for ages and tried lots of different alternatives, but it just doesn't print the data from the database.
At the moment I am just trying to get the id to print, but eventually I want to print most of the data in the database (not including the hash).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Staroids Leaderboard</title>
</head>
<body>
<table border=1px>
<thead>
<tr>
<td>name</td>
<td>score</td>
</tr>
</thead>
<tbody>
<?php
$connect = mysql_connect("localhost","root", "password");
if (!$connect) {
die(mysql_error());
}
mysql_select_db("staroids");
$results = mysql_query("SELECT id FROM scores");
while($row = mysql_fetch_array($results)) {
$name = $row['id']
?>
<tr>
<td><?php echo '$name'?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
The image below shows what it looks like in html:
This image shows the database in local host and as you can see there is lots of data, but none of the names seem to print?!
Correct your syntax where it could be
$name = $row['id']; //Put ; here
<?php echo $name;?> //Remove quotes and put ;
Select name from DB and you can get name then.It should be
$results = mysql_query("SELECT id,name FROM scores");
while($row = mysql_fetch_array($results)) {
$name = $row['name'];
?>
<td><?php echo $name;?></td>
And dont use mysql_* functions due to they are deprecated.Instead use mysqli_* functions or PDO statements.
And as #Nedstark said use try die(mysql_error()); for the errors regarding the mysql errors.
<td><?php echo $name;?></td>
or use
<td><?php echo "$name";?></td> <!--(Bad idea but works)->
Variables work in double quotes("") not in single quotes('')
<?php
session_start();
if (!(isset($_SESSION['UserName'])))
{
echo "<script type=\"text/javascript\">alert('Unauthorize user are redirected to Login page');".
header('Location:http://localhost/campus');
}
include_once "connect.php";
$find = mysql_query("YOUR SELECT STATEMENT ") or die('error');
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ST. MICHAEL's COLLEGE ILIGAN CITY</title>
<style>
AlignJst {
text-align:justify;
text-justify:inter-word;
}
pTable {
margin:2cm 4cm 3cm 4cm;
}
body {color: black; font-size: 10px; font-family: Helvetica, Arial, non-serif;}
a:link {color: #FF8C00;}
a:visited {color: #FF8C00;}
a:hover {color: #FF8C00; background: #ADD8E6; text-decoration:none;}
a:active {color: #FF0000;}
p {line-height: 2em;
font-size:85%;
color:black;
letter-spacing: 0.3em
}
h1 {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
font-size: 12pt;
color: navy;
padding-top: 12px;
padding-bottom: 3px;
}
</style>
</head>
<body>
<?php
echo "<CENTER>"."<H1>TABLE TITLE</H>" . "<BR />";
echo "<H1>SUBTITLE</H>"."</CENTER>"."<BR/>";
echo "<CENTER>"."<p>"."<b>" . "PAST MORNING PRAYER SCHEDULE" ."</b>"."</p>"."</CENTER>"."<BR/>";
echo "<table border='1' width='100%' align ='center'>";
echo "<tr>";
echo "<th>SPONSOR NAME</th>";
echo "<th>VENUE </th>";
echo "<th>DATE EVENT</th>";
echo "<th>TIME </th>";
while($row = mysql_fetch_array($find)){
echo "<tr>";
echo "<td>".$row['sponsor_name']."</td>";
echo "<td>".$row['Venue']."</td>";
echo "<td>".$row['Date_Event']."</td>";
echo "<td>".$row['Time_Event']."</td>";
echo "</tr>";
}
echo "</table>";
echo "<br />". "<br />" ."<br />";
echo "<p align = 'right'>"."Prepared By:" . $_SESSION['UserName'] ."</p>";
?>
</body>
Other than changing mysql ==> msqli, I'd recommend a couple of debug strategies, in this case I would:
fix the echo, you need to pick one of those two options:
<?php echo $variable; ?>
<?php echo "this is my variable {$variable}"; ?>
If you put a single quote PHP don't parse the content of what is about to print, it just print it as text, so what you have should print $name in the HTML...but, since I don't see any $name text in the black screenshot I think you might even not get into that loop...
a good debug strategy would be to query for something broader, i.e. "SELECT * FROM `scores`", then you can do a
<?php print_r($row); ?>
right after while ($row = mysql_fetch_array($results)) {

Categories