How to connect a HTML page to MySQL - php

How to connect a html page to MySQL for example, i want to use <?php echo $_POST['username']; ?> in a HTML file. How do i connect to MySQL.
I have tryed this:
<?php
$con=mysql_connect("HOST", "USERNAME", "PASSWORD");
mysql_select_db("DATABASE");
?>
But it did not work.

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

You need to run it on a server not just in a browser.
Download Apache, Install PHP and save the file with a .php extension. It then should work.
Then you can echo out a $_POST value but you wont need SQL for that.

You cannot add whatever PHP code to an HTML page. it have to be a PHP page.
you don't need a mysql connection to echo $_POST['username']
you should never echo any $_POST variable. After processing a POST request, web-server ought to order the browser to reload the page using GET method. Not required for the AJAX calls though.

You cannot run PHP scripts in HTML files. Your file must have .php extension to run php scripts.
You should use MySQLi instead of mysql_ functions, because these functions are depricated!

You can not do this in html page, you need to write the code in a PHP file and save it on a server then execute it.
NOTE : mysql_* functions are deprecated, you should use the newer mysqli_* or PDO features of PHP.

Of course it should not work because html is client side and you are doing connection at server side so you might need a something great called server-side scripting language to accomplish your task.
How ever you can still do it in html page with ajax but as i said you has to use server-side scripting language.

Related

Any way to get source code in actual php format from iframe

I am working with iframe in my php project ,and use iframe to load another php project also from htdocs(local storage).
and i use this javascript to get source code of single page of project from iframe window
var code=document.getElementById("myframe").contentWindow.document.documentElement.outerHTML;
and i get the code but all the php statements are in simplified format that is, for an example
<?php echo "hi"> is changed to hi
and my question is that there is any way to get in actual php format like this
<?php echo "hi"> into code variable???
If you want to get the php-sourcecode you will have to write a script for that.
Example (reader.php):
<?php
echo file_get_contents('example.php'); // or $_GET['file'] insetad of 'example.php'
The iframe would have to call reader.php?file=example.php then.
Be warned
This is highly insecure. You will have to take care of thw following things:
Sanitizing user-input
Prevent directory traversal
Limit access to only the files you want to be readable
Be very very sure there are no sensitive information in your php-files.

Is secure having MySQL in separate document? Because of include function

I learned (from internet tutorials) to create separate file, like mysql.php, with password and username.
$dbserver = "localhost";
$dbname = "";
$dbpass = "";
$dbname = "";
$db = mysql_connect($dbserver, $dblogin, $dbheslo);
mysql_select_db($dbnazev, $db);
And whenever I would need connect to mysql, I would use in my code include "mysql.php".
But doesn't it mean, that anybody in the internet can include this file to his script and get into my database?
BTW: My hosting is not using localhost, it's using mysql87.example.com... .
For your situation I can say to that it IS safe to use it that way (not my way, i like classes) and this is why:
When you start your web server there is php server started also (mod_php, php-fpm, php-cgi or other). This php server exclude from document, that will be shown to any other person that includes it thru web server.
This means that code
<!-- SOME CODE HERE -->
<?php require('mysql.php'); ?>
<!-- SOME CODE HERE ALSO -->
will be rewrited to
<!-- SOME CODE HERE -->
<!-- SOME CODE HERE ALSO -->
So anyone who includes this file will not see php code.
This means that it is safe to use it like this. But i recommend to secure direct access to such kind of files.
index.php
<?php
define ('MY_CUSTOM_CONSTANT', 42);
require('mysql.php');
// Other code
mysql.php
<?php
defined('MY_CUSTOM_CONSTANT') or die('You cannot access to this file directly');
In this case even if they include or just call this file from web - they will just get text message and code will not be executed in this case
Anyone can browse to your script, and it'll connect to the database, but the script will then immediately end. Assuming you aren't messing around with form or cookie variables in your mysql.php script, the would-be attacker is left with no way to run a query, so your database is safe.

Basic php can't run in my browser. It includes the "$" , ";" and etc. in html

I'm learning PHP coding and I can't solve this problemIt's includes the variables and the endlines.
I'm new to the language.
There is no other issue, fix your xampp problem, put your project in xampp > htdocs folder, save your file with .php extension and go to browser write http://localhost/project/page.php
Update: You are calling POST values, meaning a form (similar to a login form) has to send the values of tireqty, oilqty, and sparkqty to that page.
So you generally want to start a .php file with <?php at the very top. I would recommend doing a simple example like this:
<?php
echo '<p>1</p>';
?>
<p>2</p>
Or, change your file to reflect .html instead. You should be able to still have the php run properly there like this:
<p>1</p>
<?php
echo '<p>2</p>';
?>
If this doesn't work, please update your question to provide:
Operating System
What program you're using
What browser you're using
What version of PHP you're using
Any other information about your system
php html server

Pass from PHP to Javascript

I have a little problem here, and no tutorials have been of help, since I couldn't find one that was directed at this specific problem.
I have 2 hosting accounts, one on a server that supports PHP. And the other on a different server that does not support PHP.
SERVER A = PHP Support, and
SERVER B = NO PHP Support.
On server a I have a php script that generates a random image. And On server b, i have a html file that includes a javascript that calls that php function on server a. But no matter how I do it, it never works.
I have the following code to retrieve the result from the php script:
<script language="javascript" src="http://www.mysite.com/folder/file.php"></script>
I know I'm probably missing something, but I've been looking for weeks! But haven't found any information that could explain how this is done. Please help!
Thank you :)
UPDATE
The PHP script is:
$theimgs= array ("images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png");
function doitnow ( $imgs) {
$total = count($imgs);
$call = rand(0,$total-2);
return $imgs[$call];
}
echo '<img src="'.doitnow($theimgs).'" alt="something" />';
<img src="http://mysite.com/folder/file.php" alt="" /> ?
It's not clear, why you include a PHP file as JavaScript. But try following:
Modify your PHP Script so that it returns a image file directly. I'll call that script image.php. For further information, look for the PHP function: header('Content-type: image/jpeg')
In your JavaScript file use image.php as you would any normal image.
Include the JavaScript on server B as a *.js file.
UPDATE:
It's still not clear, why you need JavaScript.
Try as image.php:
$theimgs= array ("images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png");
function doitnow ( $imgs) {
$total = count($imgs);
$call = rand(0,$total-2);
return $imgs[$call];
}
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/" . doitnow($theimgs));
And on server b:
<img src="www.example.org/image.php"/>
You didn't specify, but I assume the two servers have different domain/hostnames. You may be running into a browser security model problem (same origin policy).
If that's the case, you need to use JSONP.
You may be using outdated sources to learn, since the language attribute is deprecated and you should use type="text/javascript" instead. It's also not clear what kind of output does the .php script produce. If it's image data, why are you trying to load it as a script and not an image (i.e., with the <img> tag)?
Update: The script is returning HTML, which means it should be loaded using Ajax, but you can't do that if it's on a different domain due to the same origin policy. The reason nothing is working now is that scripts loaded using the <script> tag aren't interpreted as HTML. To pass data between servers, you should try JSONP instead.
It seems that server A generates an HTML link to a random image (not an image). The URL is relative to wherever you insert it:
<img src="images/logo.png" alt="something" />
That means that you have an images subdirectory everywhere you are using the picture. If not, please adjust the URL accordingly. Forget about JavaScript, PHP or AJAX: this is just good old HTML.
Update
The PHP Script displays pics randomly.
Pics are hosted on server A, and they
are indeed accessible and readable
from the internet. The PHP Script has
been tested by itself, and works.
If these statements are true, Māris Kiseļovs' answer should work. So either your description of the problem is inaccurate or you didn't understand the answer...

SQL debugging in large PHP app

I am using CodeCharge Studio to finish a large PHP application. This question isn't really CCS related, but a bit more general. I have a web form that is supposed to allow CRUD capabilities with a certain SQL Server table, but the Inserts keep failing without throwing any errors. What would be the best way to debug this?
When I'm having trouble with dynamically generated SQL queries, I typically echo out the query and try running that query on the console for the DB. Or alternatively, you could write a simple PHP function that writes out strings to a file, and that way you don't have to display the query directly on your page, but instead in a log file.
See what the actually query is and then try doing that query directly on the DB. Then you know whether it's a PHP issue or a DB issue.
Then go from there, depending on the outcome.
If the query looks OK, double check that the user running the query has insert rights to the database.
I've been caught out by that before.
You can monitor all sql queries in mysql as shown in this site, once you enable logging, run the query manually and see why its failing..this should be good starting point.
In addition to what's mentioned before, I can add my recent discovery:
trigger_error(print_r($your_var,1),E_USER_ERROR);
So you can output and debug your variable, even if it's a complex script with redirects, where simple echo would not help.
Dmitri.
You should try using FirePHP and log all the SQL to your Firebug:
An Example would be:
$sql = "SELECT * FROM table"
if (!mysql_query($sql)) {
// In un successfull log to FireBug
FB::error($data, "SQL error: ".mysql_error());
}
You can also implement the FB::error call from your own function, so you can later deactivate this behaviour modifying your function:
function log_error($data, $msg){
//dont forget to deactivate in case the application goes live!
FB::error($data, $msg);
}
if (!mysql_query($sql)) {
// In un successfull log to FireBug
log_error($data, "SQL error: ".mysql_error());
}
Most of the database connection classes in CodeCharge have a 'debug' flag which will automatically write all the page's database commands at the top of the page.
For example, in an old PHP project of mine, 'Common Files' the file 'db_mysql.php' (line 27):
public $Debug = 0; ## Set to 1 for debugging messages.
Change to '1' and publish that file. Load the web page. Change back and re-publish when done.
I've used this in CCS for PHP and ASP projects, and is likely in the other languages (not sure if or where to find in .NET projects).

Categories