I am trying to realize a most simple way to query a postgreSQL db via a web site form. My current approach is the following, which results in a broken looking page (even the print command is ignored) and not reacting to submitting the values, i.e., not producing any output.
Could you give me a clue what is wrong with the code?
<!DOCTYPE html>
<head>
<title>Insert data to PostgreSQL with php - creating a simple web application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
li {listt-style: none;}
</style>
</head>
<body>
<h2>Enter Query</h2>
<ul>
<form name="insert" action="pg.html" method="POST" >
<li>RA:</li><li><input type="text" name="ra" /></li>
<li>Dec:</li><li><input type="text" name="dec" /></li>
<li>Radius:</li><li><input type="text" name="radius" /></li>
<li><input type="submit" /></li>
</form>
</ul>
<?php
$servername = "localhost";
$username = "foo";
$password = "bar";
$dbname = "foobar";
print "bla $dbname";
// Create connection
$conn = pg_connect("host=$servername user=$username, password=$password dbname=$dbname");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM foobar WHERE q3c_radial_query(RAJ2000, DECJ2000, ra, dec, radius)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "RA: " . $row["RAJ2000"]. ", DEC: " . $row["DECJ2000"]. ", r" . $row["rmag"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
Related
I want to get information from a database, and I want to put it in selectbox as option.
I tried to do it but I could not not put it what is my mistake?(db can connect I just delete server name )
I am not sure how I can put db rows in selectbox as option.
therefore, I think my code has a problem.
p.php
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
display("<option value=$row[seat_id]>",$row[seatnumber]."\n");
}
display ("</select>", "\n");
} else {
echo "0 results";
}
mysqli_close($conn);
function display($tag , $value) {
echo $tag . $value ;
}
?>
p.html
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("p.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<select id='pix' onchange='ajaxWay()'>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
If your main problem is that you are not able to embed options into your HTML, try something like this:
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("prefinal.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
?>
<select id='pix' onchange='ajaxWay()'>
<?php
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_row($result))
{
echo '<option value="' . $row[0] . ">' . $row[0] . '</option>';
}
}
mysqli_close($conn);
?>
</select>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
Note that in the above I am using your code from p.php to generate the actual content for the select options. The form should NOT submit to p.php, but to some other script that will process the form and perform the required actions. I would help more if I knew more about what you were trying to achieve!
This question already has an answer here:
Show data pulled from database, based on html form input and display in html page
(1 answer)
Closed 6 years ago.
I would like to display data from my database on page load, but I don't know how and I didn't found any functional way. Inserting works fine.
Here is my HTML code for data inserting:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="snapname">Name:</label>
<input type="text" name="snapname">
</p>
<p>
<label for="age">Age:</label>
<input type="text" name="age">
</p>
<input type="submit" value="odeslat">
</form>
</body>
</html>
PHP for connect and insert data to database:
<?php
$servername = "localhost";
$username = "admin";
$password = "***";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Could not connect to server: " . $conn->connect_error);
}
$first_name = mysqli_real_escape_string($conn, $_POST['snapname']);
$last_name = mysqli_real_escape_string($conn, $_POST['age']);
$Jmeno = $_POST['snapname'];
$Vek = $_POST['age'];
$sql = "INSERT INTO snapy (ID, username, age, date)
VALUES (0, '$Jmeno', '$Vek', CURRENT_TIMESTAMP)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Can someone help me with displaying data in HTML file?
You need to run a SELECT-request. Since you are using MySQLi you want to use something like:
$sql = "SELECT * FROM snapy";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["age"]. " yo<br>";
}
} else {
echo "0 results";
}
Found here: http://www.w3schools.com/php/php_mysql_select.asp
my name is Luis, well Im trying to make a file in html, css and php which gets information from the database and outputs it. But it has to be in the same page as the html so I can edit with CSS... thank you all!
<html>
<head>
</head>
<body>
<script>
</script>
<form action="<?php include 'file.php';?>" method="POST">
<b>Busque Jรก</b>
<input type="text" name="prestador" placeholder="prestador">
<input type="text" name="cidade" placeholder="cidade">
<input type="submit">
</form>
</body>
</html>
File in PHP:
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "test";
$namer = $_POST['prestador'];
$cities = $_POST['cidade'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name,address,city FROM tb_prestadores WHERE name = '$namer' AND city = '$cities'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "name: " . $row['name']. " Endereço - : " . $row['address']." Cidade :".$row['city']."<br>";
}
} else {
echo "It is going to else";
}
$conn->close();
?>
You are including / inserting the file wrongly.
What you should do:
1) Copy your html code and paste it at the bottom of your php code i.e. after the ending '?>' tag. Your code should look like this:
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "test";
$namer = $_POST['prestador'];
$cities = $_POST['cidade'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name,address,city FROM tb_prestadores WHERE name = '$namer' AND city = '$cities'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "name: " . $row['name']. " Endereço - : " . $row['address']." Cidade :".$row['city']."<br>";
}
} else {
echo "It is going to else";
}
$conn->close();
?>
<html>
<head>
<!-- include your css here-->
</head>
<body>
<script>
</script>
<form action="" method="POST">
<b>Busque Jรก</b>
<input type="text" name="prestador" placeholder="prestador">
<input type="text" name="cidade" placeholder="cidade">
<input type="submit">
</form>
</body>
</html>
Btw, this is not the 'optimal' way to code applications. Please look into Smarty or some other templating language as well as MVC once you get the hang of php and html basics. Good luck!
To begin with, your <?php include 'file.php';?> is miss-placed and should not be in the action tag of your form rather it should be right before it, like so:
<html>
<head></head>
<body>
<?php include 'file.php';?>
<form action="" method="POST">
<b>Busque Jรก</b>
<input type="text" name="prestador" placeholder="prestador">
<input type="text" name="cidade" placeholder="cidade">
<input type="submit">
</form>
</body>
</html>
so I am trying to display multiple results from a database when a query is searched, the query is passed from a search box on another page.
I have it displaying one result, but that is all it will display.
I need it to display all the results that are relevant to the search query.
the php code is below
<meta charset="UTF-8">
<?php
$mysqli = new mysqli('localhost', 'scott', 'tiger','courses');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
$search_result = $result->fetch_assoc();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<h3><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
</body>
and the code for the search bar
<!doctype html>
<html>
<Head>
<meta charset = "utf-8">
<title>Search</title>
</head>
<body>
<h2>Search</h2>
<form name="search" method="post" action="SearchResultsPage.php">
<input name="searchBar" type="text" size="40" maxlength="60" />
<input type="submit" name="Submitsearch" value="Search" />
</form>
</body>
Does anyone have any suggestions?
Thanks in advance;
You will need to place it in a while loop to show multiple results, the fetch function you're using will only retrieve one row, if you place it in a loop you can keep fetching until there is nothing to fetch:
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<?PHP while($search_result = $result->fetch_assoc()) { ?>
<h1><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
<?PHP } ?>
</body>
P.S. your code is vulnerable to SQL injection, you should read about prepared statements. More Info on that
You can iterate over your query results with a while loop. To complete the example I added the necessary data cleaning.
<?php
// function to clean post data
function cleanPost(&$value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = cleanPost($v);
}
return $value;
}
else {
$value = mysql_real_escape_string($value);
return trim(htmlentities(strip_tags($value)));
}
}
// search function
function search() {
// check if post data is set
if (isset($_POST['searchBar'])) {
// make link with db
$link = mysqli_connect('localhost', 'scott', 'tiger','courses');
if (!$link)
return false;
}
// clean your post data
$cleanPostData = cleanPost($_POST);
// query
$sql = "SELECT title, summary, id FROM course WHERE title LIKE '%".$cleanPostData['searchBar']."%'";
$result = mysqli_query($link, $sql);
// iterate over results
if (isset($result) && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// here is your data
echo $row['title'] . "< br/>";
echo $row['summary'] . "< br/>";
echo $row['id'] . "< br/>";
}
}
}
}
// call search function
search();
?>
I've found similar questions, but have been unable to tie them into my example. I am very new to PHP and completely self teaching.
At present I have a form for entering a new customer. In that form I want the user to be able to select an existing DB item (business) and insert that BusinessID into the CUSTOMER table. My problem is that I can GET the BusinessID, but then I can't POST that same ID with the other field inputs. Code below
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>New Contact</title>
<!--Declare CSS and JavaScript-->
<link rel="stylesheet" type="text/css" href="RealtyCRM_Style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery.resmenu.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
$('.toresponsive').ReSmenu();
});
</script>
<!--Begin Header Code-->
<!--Begin Header Code-->
<div class="BodyHeader">
<div>
</div>
</div>
<!--Begin Menu Code-->
<div class="menu_container" style="position:relative; z-index:11;">
<ul class="toresponsive">
<li>Log In</li>
<li>Contact</li>
<li>News</li>
<li class="current-menu-item">Dashboard
<ul>
<li>Add New Data</li>
<li>Update Data</li>
<li>Search</li>
<li>Report</li>
<li>Admin Page</li>
<li>Log Interaction</li>
</ul>
</li>
</ul>
</div>
<br>
<!--Begin Dashboard Buttons Code-->
<div class="DashboardButtonsTop">
<h1 class="centeredDashBoardButtonInactive">New Retailer</h1>
<h1 class="centeredDashBoardButton">New Contact</h1>
<h1 class="centeredDashBoardButtonInactive">New Property</h1>
</div>
<hr style="width:700px; height:5px;">
<br>
<br>
<!--END Dashboard Buttons Code-->
<?php
if(isset($_POST['add']))
{
$dbhost = 'localhost';
$dbuser = 'leasingl_dbwrite';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$contactFirstName = addslashes ($_POST['contactFirstName']);
$contactLastName = addslashes ($_POST['contactLastName']);
}
else
{
$contactFirstName = $_POST['contactFirstName'];
$contactLastName = $_POST['contactLastName'];
}
$contactPhoneNumber = $_POST['contactPhoneNumber'];
$contactEmail = $_POST['contactEmail'];
$Business = $_POST['BusinessID'];
$sql = "INSERT INTO Contact ". "(ContactFName,ContactLName, ContactMobilePhone, contactEmail, BusinessID, CreatedDate) ". "VALUES('$contactFirstName','$contactLastName','$contactPhoneNumber', '$contactEmail', '$Business', NOW())";
mysql_select_db('applicationDatabase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "<div style='text-align:center;'>Entered data successfully\n</div>";
echo "<br><div><a href='contactdataentry.php' class='redirectButton'>Add More Contacts</a>\n</div>";
echo "<br><div><a href='dashboard.php' class='redirectButton'>Return to Dashboard</a></div>";
mysql_close($conn);
}
else
{
?>
<div class="Form_container">
<form method="post" action="<?php $_PHP_SELF ?>">
Contact First Name<br>
<input class="largeInput" type="text" name="contactFirstName" ID="contactFirstName"><br>
Contact Last Name<br>
<input class="largeInput" type="text" name="contactLastName" ID="contactLastName"><br>
Contact Phone Number<br>
<input class="largeInput" type="text" name="contactPhoneNumber" placeholder="### - ### - ####" ID="contactPhoneNumber"><br>
Contact Email<br>
<input class="largeInput" type="text" name="contactEmail"><br>
Business<br>
<?php
$servername = "localhost";
$username = "leasingl_dbread";
$password = "password";
$dbname = "applicationDatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT RetailerID, RetailerName FROM Retailer ORDER BY RetailerName DESC";
$result = $conn->query($sql);
?>
<select style='text-align:center;' class='largeInput' name='Business' ID='Business'>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["RetailerID"]. "'>" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option><br><br>";
}
} else {
echo "0 results";
}
?>
</select><br><br>
<?php
$conn->close();
?>
<input name="add" type="submit" id="add" value="Add Contact" class="button">
</form>
<br>
<hr style="width:400px; height:10px;">
</div>
<?php
}
?>
</body>
</html>'
So being able to insert the value from my drop down is the main issue. Additionally, I'm sure there is unnecessary / incorrect code in what I posted, I've been piecing together examples one at a time.
Thank you for all the help, if I can get this working I can have a functioning basic version of my application
EDIT
I have successfully prepopulated my drop down, and the user then chooses from that list. I want to pass that choice via my INSERT statement. I worry that the two different CONNECTIONS which I establish are part of the reason my INSERT won't recognize $Business
It appears you are referring to GET in a confusing way. In PHP there is $_GET and $_POST variables, and when you mention GET in all-caps, in implies you are using $_GET - which in fact you are not.
The solution - as I understand the question - is actually fairly straightforward.
Inside your form, add a hidden input that stores (and then passes) the BusinessID variable, like so:
<input type="hidden" name="BusinessID" value="<?php echo $Business; ?>">
As you mention you are just learning, here's some additional tips:
Name your variables consistently throughout. If the name of the database column is BusinessID, then name your variable $businessID" and your inputBusinessID".
Kudos to you for good indenting / formatting! That will save you gobs of time when troubleshooting / reading your own code!
EDIT
If what you are trying to do is pre-select the record in the dropdown, then alter your loop like so:
while($row = $result->fetch_assoc()) {
// Note: I've removed the <br> tags here, they don't belong in a select dropdown
echo "<option value='". $row["RetailerID"]. "'";
// If the ID matches, make this the selected option
// NOTE: Per my tip above, I'd strongly recommend changing the variable name $Business to match the field name - $RetailerID in this case
echo ($row['RetailerID'] == $Business) ? ' selected' : '';
echo ">" . $row["RetailerName"]. " - " . $row["RetailerID"]. "</option>";
}