I have a MySQL database on my local machine and am trying to query it with PHP.
I've written out the following HTML/PHP code. When I open this HTML file in Chrome, this is what is displayed. Why does the browser treat this code as text?
ID Project Code'; while ($row = mysqli_fetch_array($response)){ echo '' . $row[Id] . '' . $row[Project_Code] . ''; echo ''; } echo ''; } else { echo "couldn't connect do it"; echo mysqli_error($dbc); } mysqli_close($dbc); ?>
code:
<HTML>
<body>
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'root');
DEFINE ('DB_HOST', 'my_local_ip');
DEFINE ('DB_NAME', 'my_db');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("couldn't connect");
$query = "SELECT Id, Project_Code FROM database.projects";
$response = #mysqli_query($dbc, $query);
if ($response){
echo '<table>
<td>ID</TD>
<td>Project Code</TD></table>';
while ($row = mysqli_fetch_array($response)){
echo '<tr><td>' .
$row[Id] . '</td></td>' .
$row[Project_Code] . '</td></td>';
echo '</tr>';
}
echo '</table>';
} else {
echo "couldn't connect do it";
echo mysqli_error($dbc);
}
mysqli_close($dbc);
?>
</BODY>
</HTML>
It is Because you are not running your code with apache/php/mysql.
If you are using windows package like wamp put it in www directory and access it through localhost, not directly open it in the browser, otherwise browser will treat it like plain html.
i've opened it as you were opening in chrome:
You should access your script using localhost and make sure your wamp (or whatever server package your are using) should be running.
PHP unlike javascript/HTML is a server side language. It runs on the server and outputs the generated content to the browser.
So for example
<?php
if(empty($a)) {
echo ':)';
} else {
echo ':(';
}
?>
The only part that makes it to the browser would be :).
The issues you are running into are
a) your file is .html. PHP won't run as such unless your server configuration is modified to do so.
b) your files are being executed on your local machine which doesn't have PHP installed.
Solutions:
a) Install PHP on your local machine; http://php.net/manual/en/install.php
b) Move to a hosted server (this might be easier since they will have support for configuration issues)
(lettering unrelated to issues lettering)
To be more specific your whole PHP code is outputted to the browser but the
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'root');
DEFINE ('DB_HOST', 'my_local_ip');
DEFINE ('DB_NAME', 'my_db');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("couldn't connect");
$query = "SELECT Id, Project_Code FROM database.projects";
$response = #mysqli_query($dbc, $query);
if ($response){
echo '<table>
Is all read as one element <?php until the > of the <table>.
Also while learning try to never use the #. That suppresses errors and those might (95% of the time, will) be useful to you.
After you installed Apache,MySQL and PHP
(You can try XAMPP or WAMP as mentioned in other answers.)
you can test this code:
(For XAMPP put your code in xampp\htdocs folder ,
name like something.php
to run. browse to localhost/something.php)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'database');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("couldn't connect");
$query = "SELECT Id, Project_Code FROM database.projects";
$response = mysqli_query($dbc, $query);
?>
<?php
if ($response){
echo '<table>
<td>ID</td>
<td>Project Code</td>';
while ($row = mysqli_fetch_array($response)){
echo '<tr>'.'<td>'.$row['Id'].'</td><td>'.$row['Project_Code'].'</td></tr>';
}
echo '</table>';
} else {
echo "couldn't connect do it";
echo mysqli_error($dbc);
}
mysqli_close($dbc);
?>
</BODY>
</HTML>
Related
so I've been trying to get this working for a few days now and I am completely lost. I've tried following a few of the answers on here but I can't seem to figure out what I need to change to adapt it to my database.
There have been complex and simple solutions I have seen, but what I am attempting at the minute is this:
...
<?php
echo "";
define('DB_USER', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
define('DB_NAME', 'username_test');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' . mysqli_connect_error() );
mysqli_set_charset($dbc, 'utf8');
?>
<?php
public function get_data()
{
$mysqli= new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Couldn't connect".mysqli_connect_error());
$sql="SELECT Staff_Surname, Staff_Forename FROM users";
$result=$mysqli->query($sql) or die($mysqli->error);
while ($row=$result->fetch_array(MYSQLI_ASSOC))
{
echo "<option value=\"".$row["Staff_Surname"]."\" selected>".$row["Staff_Forename"]."</option>";
}
}
?>
<html>
<body>
<select name="abc" id="xyz">
<?php get_data(); ?>
</select>
</body>
</html>
...
which just results in a bunch of errors when I try to run it in a browser. I am using Microsoft Expression Web 4 and XAMPP.
This is a screenshot of the SQL database I just need to pull the forename and surname into a dropdown box:
SQL database
Any help you guys can offer would be really appreciated. Thank you.
Sorry, in the preview it looked like it showed what the error was. When I try to run the code in a browser I get this: enter image description here
Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in index.php on line 17
Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'username'#'localhost' (using password: YES) in index.php on line 17
Warning: mysqli::query(): Couldn't fetch mysqli in index.php on line 19
Warning: get_data(): Couldn't fetch mysqli in index.php on line 19
Change
$mysqli= new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die("Couldn't connect".mysqli_connect_error());
to
$mysqli= new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Couldn't connect".mysqli_connect_error());
Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting end of file in index.php on line 15
Change
public function get_data()
to
function get_data()
These changes should take care of all the errors you are receiving.
Code with #stealthyninja edits:
<?php
echo "";
define('DB_USER', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');
define('DB_NAME', 'username_test');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die('Could not connect to MySQL: ' . mysqli_connect_error() );
mysqli_set_charset($dbc, 'utf8');
?>
<?php
function get_data()
{
$mysqli= new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die("Couldn't connect".mysqli_connect_error());
$sql= "SELECT Staff_Surname, Staff_Forename FROM users";
$result= $mysqli->query($sql) or die($mysqli->error);
while ($row=$result->fetch_array(MYSQLI_ASSOC))
{
echo "<option value=\"".$row["Staff_Surname"]."\"selected>".$row["Staff_Forename"]."</option>";
}
}
?>
<html>
<body>
<select name="abc" id="xyz">
<?php get_data(); ?>
</select>
</body>
</html>
EDIT:
Issues connecting to MySQL. First the usernames and passwords are
here: login info
The XAMPP control panel: XAMPP
The testcode that worked previously: Registration
And the error it now presents: Registration Error
I don't think I have changed anything from when it worked before. I built the Registration page following a tutorial in the book "PHP and MySQL for Dynamic Web Sites fifth edition" by Larry Ullman.
I have hosted my website on Linux server and I want to connect MS SQL database. i have used PHP in programming. I have contacted to both server provider and they helped in their extent. But my issue is not solved Can you guide me what to do. My code is below.
While I run this it is showing " could not find driver1"
Please guide me. Thanks in advance
<?php
//echo phpinfo();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>testing</h1>
</body>
</html>
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'server:port';
$myDB = "DatabaseName";
// Connect to MSSQL
$link = mssql_connect($server, 'username', 'password');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else
{
echo "success";
}
?>
<?php
try {
$conn = new PDO("sqlsrv:Server='server_name';Database=database_name", 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
die(print_r($e->getMessage() ));
}
$tsql = "select * from table_name";
$getResults = $conn->prepare($tsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach ($results as $row) {
echo $row['0'].' '.$row['6'];
echo "<br>";
}
?>
I'm coding a web service for iOS in Php. I'm trying to retrieve data from server through php but the response is null.The server is MSSql Server 2014.
<?php
define ('DB_HOST', '****.net');
define ('DB_USER', '****');
define ('DB_PASS', '******');
define ('DB_NAME', '*******');
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_NAME, $dbc);
if (mysql_select_db){
echo "Done";
}else{
echo "Die";
}
$sql_select = "SELECT * from ClientChk";
$records = mysql_query($sql_select);
$count= 1;
while($result = mysql_fetch_array($records))
{
if ($result == nil){
echo "Nil!";
}
}
echo json_encode($result['Id']);
?>
This is a bad example of doing this.
1) You have to check if the connection was successful.
2) If use MSSQL, then you can't use mysql_ commands.
3) nill doesn't exist in php, should be 'null'
$SERVER = '127.0.0.1';
$DB = 'test';
$USER = 'username';
$PASSWORD = 'password';
$db = new PDO("sqlsrv:server=$SERVER;database=$DB;", $USER, $PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$query = "SELECT * FROM ClientChk";
$result = $db->query($query)->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $ex) {
$ex->getMessage();
echo $ex;
}
echo json_encode($result);
So, the problem is, that you try to connect to a MSSQL database, with a MySQL database connector.
To connect to a MSSQL database, you can use the following methods:
mssql_connect(): It uses a quite similar syntax to mysql, but it is removed as of php 7.0, so I advice against it's usage even if you using an earlier version of php.
PDO class: It's differs a lot from the older function style sql connectors, but it is the preferred way by many.
sqlsvr_connect(), obdc_connect(): If you prefer a function based connector instead of the PDO class, and you don't want to use the deprecated mssql_connect, I recommend choosing one of these.
I hope, I could be of any help.
I've just started learning php and I'm having trouble finding the problem when I get it to connect to the database and run an 'INSERT' query. I think the problem is in my connection.php file.
insert.php:
<?PHP
echo "into";
include("connection.php");
echo "connected";
$table = blog;
$sql = "INSERT INTO $table SET
Title = '$_POST[title]',
Description = '$_POST[description]',
Content = '$_POST[content]'";
$query = #mysql_query($sql);
echo "complete";
echo $_POST[title];
echo $_POST[description];
echo $_POST[content];
?>
connection.php:
<?php
echo "connection file reached";
$conn = mysql_connect(localhost, user, pass);
mysql_select_db(test, $conn);
echo "connected";
?>
Any advice on my code, or how I could solve this problem would be much appreciated.
EDIT: I'm thinking that it never gets to the connection.php file because it shows the "into" at the top of insert.php but not the "connection file reached" at the top of connection.php. Is that call correct to that file?
Thanks
Readup on php constants, variables and strings!
define('foo','bar'); // foo == 'bar';
$foo = 'bar'; // $foo == 'bar'
Please use mysqli_* as mysql_* is depreciated.
$conn = mysql_connect(localhost, user, pass);
probably should be
$conn = mysql_connect('localhost', 'user', 'pass');
you have written
#mysql_query($sql)
as well as a lot other problem it's structure is also wrong the problem might be from version of your language as recommendation of php you should not use mysql any more use mysqli or PDO
please ignore that it is old code im am testing
Having an issue where by I am unable to show specific user data from my db yet I can show the row of data. I can show the username using <?php echo htmlentities($_SESSION['username']); ?>but if I try and throw out email for example it dosnt like it. but if I do this....
<?php
$con = mysql_connect("localhost","***","***");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dmh", $con);
$result = mysql_query("SELECT * FROM members");
while($_SESSION = mysql_fetch_array($result))
{
echo $_SESSION['email'];
}
mysql_close($con);
?>
Like I say it chucks up the row - in regards to the above mention of pulling data from the DB via <?php echo htmlentities($_SESSION['username']); ?> this is handled by pulling in by db_connect.php file and also my functions file.
Try the following, unsure if that's the result you wish to get.
Using mysqli_* functions instead of mysql_*.
<?php
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_NAME', 'xxx');
$mysqli = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
$result = mysqli_query($mysqli,"SELECT * FROM members ");
session_start();
while($row = mysqli_fetch_array($result))
{
$_SESSION['email']=$row['email'];
}
echo $_SESSION['email'];
echo "<hr>";
echo "TEST";
echo "<hr>";
var_dump($_SESSION['email']);
mysqli_close($mysqli);
?>
I wouldn't access the $_SESSION like that. You could try:
$result = mysql_query("SELECT * FROM members");
while($meh = mysql_fetch_array($result))
{
$_SESSION['email']=$meh['email'];
echo $meh['email'];
}
That way your other session variables don't get overridden when you go to this page. The only other thing that I can suggest is trying print_r($meh); to see what data is actually getting put in the array. If it's attaching to numbers, there's a high chance you need to access it like echo $meh[0].