How to link MySQL to html - javascript

I am trying to create a website using html in gedit, and i need to be able to log in or register at the homepage which then takes the user to their page on the website, where they are able to input a message, i need the message to go into a database, and to be able to show it at another page on the website. I am confused on how to link html to MySQL when information is created using a form.
I would appreciate if anyone can help me please,
Thanks in advance.

You need to use some server side language to do this. The way it would work is the form would have a URL associated with it for where it would submit the data to. This page should be a PHP script or ASP page or something like that.
Once you have a PHP script you can connect to the database and insert in the records as required with the data.
Here is a good resource if you're not familiar with this:
http://www.w3schools.com/php/php_mysql_insert.asp

You will need to use some sort of server side language like PHP for example. With PHP you can connect to a DB and insert data according to forms that you submit.

I know this answer to your query comes very late (6 years too late) but for the sake of all the newbies out there who googled and reached this page in search of the same question, here's a good response:
Tutorial to use an HTML web-page to interact with a MySQL database using PHP
The tutorial takes you through establishing a mysql connection using php on a web page, connecting to a mysql table and retrieving the results and displaying them back on the web page.
This tutorial uses the PHP MySQL commands:
mysqli_connect
mysqli_query
mysqli_fetch_array
mysqli_close
The Plan
make the connection and select the database
perform the query on the table
print out the data
close the connection
First Up – Connecting to a MySQL database
You need your MySQL server address (if the database is on the same server as the web server it will most likely be localhost or 127.0.0.1), username, password and database name. Create a filenamehere.php file and open and close the php code with tags before the html, you can put regular html after it. Open the file in a browser and you should see nothing apart from the title tag, if you see the error the username/password or database name may be wrong.
PHP will require that mysqli is enabled (it is on most PHP set ups).
<?php
//Step1
$db = mysqli_connect('localhost','username','password','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
</body>
</html>
The variable $db is created and assigned as the connection string, it will be used in future steps. If there is a failure then an error message will be displayed on the page. If it is successful you will see PHP connect to MySQL.
Performing a database query
The mysql query is actually performed in the body of the html page, so additional php opening and closing tags will be required. For the query we are going to specify a read of all fields from a given table. The $query variable selects all rows in the table. You just need to use your table name.
<?php
//Step1
$db = mysqli_connect('localhost','root','root','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
//Step2
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying database..');
?>
</body>
</html>
Again the returned page in the browser should be blank and error free, if you do receive the error – ‘Error querying database..’ check the table name is correct.
Put the data on the page
Here we are making a $result variable which stores the query we just made above, now we just need to go through all the rows of that query which we need mysqli_fetch_array which stores the rows in an array, so now we are storing the $result in mysqli_fetch_array and passing that into a variable called $row.
The $row now can be output in a while loop, here the rows of data will be echoed and displayed on the page to when there is no longer any rows of data left, this example uses 4 fields in the table first_name, last_name, email and city.
<?php
//Step1
$db = mysqli_connect('localhost','root','root','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
//Step2
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying database.');
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_array($result)) {
echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'<br />';}
?>
</body>
</html>
Here you should see the all data as output from your table.
Closing off the connection
Closing the connection will require another set off opening and closing php tags after the closing html tag. It is good practice to close the database connection when the querying is done.
<?php
//Step1
$db = mysqli_connect('localhost','root','root','database_name')
or die('Error connecting to MySQL server.');
?>
<html>
<head>
</head>
<body>
<h1>PHP connect to MySQL</h1>
<?php
//Step2
$query = "SELECT * FROM table_name";
mysqli_query($db, $query) or die('Error querying database.');
//Step3
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
while ($row = mysqli_fetch_array($result)) {
echo $row['first_name'] . ' ' . $row['last_name'] . ': ' . $row['email'] . ' ' . $row['city'] .'<br />';}
//Step 4
mysqli_close($db);
?>
</body>
</html>
Database connections should always be closed off. You do not need to keep the connection variable $db after the initial connection but is considered best practice.

You need to use PHP, try WAMP it has PHP, MYSQL databse
here is a simple form
Your database table test
create table test
(id int not null auto_increment primary key,
firstname nvarchar(20)
);
Then using Server side PHP
//tst.php file
<?php
$connect=mysql_connect('hostname','username','password');
mysql_select_db('databaseName');
if(isset($_POST['submit']))
{
$firstname=mysql_real_escape_strings($_POST['firstname']);
$ret=mysql_query("insert into test(firstname) values ('$firstname')")
}
?>
<html>
<head> </head>
<body>
<form method="post">
<input type="text" name="firstname" />
<input type="submit" name="submit" Value="Submit" />
</form>
</body>
</html>

Related

PHP get information from database when echoed html code is clicked

In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}
As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation
I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.
you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.

Redirect and popup when sql is done

I want to get my application when a item is deleted pop up a messege and redirect to another page. I used javascipt for the popup and php header for the redirection. Now its only doing or the popup or the redirect depending which one is listed first. how do i fix this?
<?php
session_start();
require_once('../../includes/mysql_config.php');
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: ../../login.php');
$Cursist = mysqli_query($con, "SELECT id FROM users WHERE id =".$_SESSION['id']);
if(!$Cursist){
header('location: ../login.php');
}
$test = $_GET['id'];
$sql = "DELETE FROM cursus WHERE id = $test";
$result = mysqli_query($con, $sql);
if ($result) {
echo "<script type='text/javascript'>alert('Verwijdert!')</script>";
header("Location: ../cursussen.php?destoyed=true&destroyed_id=".$_GET['id']);
}else {
echo "mislukt";
}
?>
If you send sometrhing before header will not work. You can use only header before sending sometrhing to the client.
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
http://php.net/manual/en/function.header.php
You could do with javascript but It not recommended because the user could have javascript disabled:
echo "<script type='text/javascript'>";
echo "alert('Verwijdert!')";
echo "document.location.href='index.html'";
echo "</script>";
The best way is to use session and header, you can save a var in session and show a message when the var is true and when you show the messasge delete the session var
delete.php
$_SESSION['deleted'] = true;
header("Location: index.php);
index.php
<?php if($_SESSION['deleted']){ ?>
<?php unset($_SESSION['deleted']) ?>
<div>Item was deleted</div>
<?php } ?>
Well, the problem is that the redirect immediately moves you to a new page, so any javascript on the old page becomes irrelevant. You might be able to use a delay before redirect so that the javascript alert can display.
Otherwise, introduce a variable that you send to the redirect destination page, and use this variable to trigger a javascript popup there.

How do i reload the page after the sql statement has been submitted

I am using the following code to try and insert data into my database. The data works fine and i do this using a form. The form has a submit button that i will but the code in bellow the following code. I am using localhost to run my web application.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO PRODUCTS (P_Name, P_Description, P_Price) VALUES ('$_POST[Name]', '$_POST[description]', '$_POST[Price]' ) ";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
the submit button:
<div id="theSubmit">
<input type="submit" name="submit">
</div>
At the moment when i click submit i get taken to a page display the text New record created successfully. However I would like it to reload the page.
I am aware of the javascript location.reload(); is this what I have to use, if so where?
You should reload after execution of your sql like this.
$_SESSION['msg'] = "New record created successfully";
header("Location: $url"); // tell the client to load $url
exit(); // stop further execution of the current script
the $msg should be set via session to be able to show the msg after reload.
If you do it like that it is no problem if the user klicks the back button or do a page reload.
After reload do:
if(isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
Use:
header("Location: $_SERVER[REQUEST_URI]");
exit;
This will redirect the user to the the same page using a GET method, reloading it.
If you are not displaying any DOM Elements, or doing any Header requests prior that PHP Script you can always use the php function
header('Location: your-url.com');
exit();
to reload a website.
if there are header requests prior that header function this solution wont work so you can add that JS code at the bottom of your script so it gets fired after you have dealt with the form.

Fetch altered data after page is updated

When update button is submitted a function edit_page() is called. This function alter the database table row with new data entered.
This works fine table altered correctly entries are ok.
But problem is that when update button is submitted
1. Entries is database inserted or altered correctly.
2. But when page reloads content of this updated page remains as it is as previous or like before updation on front end or just after submission.
My code:
<?php
function edit_page()
{
add_cat();
global $page_id;
?>
<?php
if (isset($_GET['page_action']) && ($_GET['page_action'] == 'edit'))
{
$page_id = $_GET['post'];
}
?>
<?php
$page_id = $_GET['post'];
$result = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'"); //execute the SQL query and return records
$row = mysql_fetch_array($result);
$page_title = $row['page_title'];
$page_content = $row['page_content'];
?>
<form method="post" action="" name="edit_page" class="edit_page">
<h4>Page Title:</h4> <input type="text" name="title" class="title" placeholder="Add title of the Page" required value="<?php echo $page_title;?>"/><br/>
<h4>Page Content:</h4><br/>
<textarea cols="80" id="content" name="content" rows="10"><?php echo $page_content;?></textarea>
<input type="hidden" name="page_edits" value="yes" />
<input type="submit" name="edit_page" class="button" value="Update"/>
<?php
save_edits(); }
function save_edits()
{
if (isset($_POST['edit_page']) && $_POST['page_edits'])
{
$page_id = $_GET['post'];
$page_id = $_GET['post'];
$page_title = $_POST['title'];
$page_content = $_POST['content'];
$date = date('Y-m-d h:i');
$query = "UPDATE pages SET page_title='$page_title', page_content='$page_content', date_gmt='$date' WHERE page_id = '$page_id'";
$result = mysql_query($query) or die("Unable to create Page: " . mysql_error());
}
}
?>
<div class="right_sidebar">
<?php edit_page();?></div>
Finally, my mean is that i just want functionality like wordpress in which when update button is clicked just after that we see updated data.
You're doing PHP the procedural way here. That means the statements are executed one after another so the problem lies in the way you place your statements.
In your code, you are displaying the form first and only then updating it, so that's why the previous values get fetched although update is happening only later.
Solution: The function save_edits() and its call should come first followed by edit_page().
Another important thing in terms of security, you are directly inserting the value you get from the address bar. Right now the way it is, someone can drop your whole table by writing in a piece of code. You could use mysql_real_escape_string() to prevent it (although not totally) or better yet:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Lastly, you are not closing your <form> tag.

JQuery not changing the content of div from even numbered links?

Thanks for taking the time to look at this post.
So I have managed to do my task to a point.
I am pulling data from a database called posts with the following fields: id, account_name, data, heading, subheading, videos, voice_notes, music, images, post_date, date_for_post.
So This is the process:
1 - Pull data from db and put into array
2 - Make unordered list from array with links
3 - when link is clicked, fill content div with that posts data.
Now it will load the specific posts data on odd numbered links, but on even numbered links it wont load the data into the container? using the same method? I have re-ordered the lists and still, even numbered list items just wont work. Am I doing something wrong?
I have also tried putting in a blank list item in between the posts to see if it were the list items themselves that were not calling the function, but it seems that it is only the even links.
I don't know how else to explain it, here is my code:
<?php
$connection=mysql_connect('localhost', 'username', 'password');
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db('dbname', $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "SELECT * FROM posts";
$result = mysql_query($query);
if(!$result){
die('Invalid query' . mysql_error());
}
$posts = array();
while($line = mysql_fetch_array($result, MYSQL_ASSOC)){
$posts[] = $line;
}
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/content.js"></script>
</head>
<body>
<div id="content">some data</div>
<div id="links">
<ul>
<?php
foreach ($posts as $post) {
$data = "'".$post['data']."'";
echo '<li>'. $post['date_for_post'] .'</li>';
}
?>
</ul>
</div>
</body>
and the getContent function:
function getContent(element, data){
$(element).text(data);
}
I cannot figure out why. here is a graphical representation of whats happening:
I have tried inserting black list items to see if it was the actual even list items not calling the function, but it is the even list items with the content inside that wont work, if that makes sense?
Please help as I have no clue what is going on and how to fix it.
Thanks in advance!
UPDATE
it seems to be that the longer posts dont display, the shorter do. I have the data type in the database set to text, not varchar. So where is the issue with size? Is there a maximum size I am allowed to put through the JQuery function? Or in the database? Because it shows in the database, but not on the post
I think the problem is with quotes and double quotes here in your code:
$data = "'".$post['data']."'";
echo '<li>'.$post['date_for_post'] .'</li>';
Check the source of generated HTML page. There should be incorrect 'li' tags. I suggest change your code to this:
$data = $post['data'];
echo '<li>'.$post['date_for_post'] .'</li>';
Hope it helps.
Also, check if the quotes in text from database are causing this problem.
It's hard to see what's going on, try to provide a jsfiddle. Even though you are using php, you can create a manual feed of json data and test out the javascript. To make it less confusing, have the data stored in a ...
<script>
$(document).ready(function () {
var dbObj = <?php $post ?> // $post object to be formatted in json
var render;
for (obj in dbObj) {
render = render + '<li><a href="#" onclick=getContent("#content", ' + obj.data + '");>' +obj.date+ '</a></li>'
$('#links ul').append(render);
});
</script>
If that works and you really want to have the php print out the list, then you can replace it with the php foreach; these days, developers are allowing the client-side to render templates/html and at least you'll know the js works this way! :-)
<?php
foreach ($posts as $post) {
echo '<li><a href="#" onclick=getContent("#content", "'. $post["data"] .'");>'. $post['date_for_post'] .'</a></li>';
}
?>

Categories