PHP Error Connecting to Database - php

Background Information:
I am trying to create a TODO App
<?php
require_once 'app/init.php';
$itemsQuery = $db->prepare("
SELECT id, name, done
FROM items
WHERE user = :user
");
$itemsQuery->execute([
'user' => $_SESSION['user_id']
]);
$items = $itemsQuery->rowCount() ? $itemsQuery : [];
foreach ($items as $item) {
echo $item['name'], '<br>';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Darshil Patel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="list">
<h1 class="header">To do.</h1>
<ul class="items">
<li>
<span class="item">Pick Up Shopping</span>
Mark as done
</li>
</ul>
<form class="item-add" action="add.php" method="post">
<input type="text" name="name" placeholder="Add a New Item" class="input" autocomplete="off" required>
<input type="submit" value="Add" class="submit">
</form>
</div>
INIT.PHP:
<? php
session_start();
$_SESSION['user_id'] = 1;
$db = new PDO('msql_dbname= u352634928_list;host=mysql.hostinger.co.uk', 'mysql.hostinger.co.uk', 'password');
if(!isset($_SESSION['user_id'])) {
die('You are not signed in');
}
I am not sure why I am getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'invalid
data source name' in /home/u352634928/public_html/app/init.php:7 Stack
trace: #0 /home/u352634928/public_html/app/init.php(7):
PDO->__construct('msql_dbname=u35...', 'u352634928_list', 'password')
1 /home/u352634928/public_html/index.php(2): require_once('/home/u35263492...') #2 {main} thrown in
/home/u352634928/public_html/app/init.php on line 7

You have left a space between the <? and the php. So at the very first do it <?php

Simple typo:
Change
<? php
To
<?php
Basically, all PHP statements end with semi colon ;.
And in your case, your PHP starts with <? you have added space before php.
So, php is a statement and that is not ended with ;.
That is the reason behind parse error.

change <? php to <?php, remove the space in between.
require_once
pdo

This is the right syntax to connect with Mysql database :
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
for you
$db = new PDO("mysql:host=mysql.hostinger.co.uk;dbname= u352634928_list", 'mysql.hostinger.co.uk', 'password');

Related

problem declaring in php for database in xamp

I am learning to use php, html and xamp. what happens is that I have an error because
does not recognize a statement I make on the page to get the list (query) of what you have
the database. the problem is when on the other page it tells me that empleadoID is not defined, according to this the empleadoID is not defined and i don't know why
here is the list. this is where I define it in the last 2 echo:
<?php
include("basededatos.php");
$conexionbd=conectar_bd();
$query ="SELECT id,nombre,edad FROM empleado;";
$resultado = mysqli_query($conexionbd,$query);
mysqli_close($conexionbd);
?>
<html>
<head>
</head>
<body>
<h1>Lista de empleados</h1>
<ul>
<?php
while ($registro = mysqli_fetch_assoc($resultado))
{
echo '<li>'.$registro['nombre'].' ('.$registro['edad'].'aƱos)';
echo ' Modificar</li>';
echo ' Eliminar</li>';
}
?>
</ul>
</body>
</html>
This is where he tells me that he doesn't exist:
<?php
include("basededatos.php");
$conexionbd = conectar_bd();
$query = "SELECT id,nombre,edad FROM empleado Where id".$_GET['empleadoID']."LIMIT 1";
$resultado=mysqli_query($conexionbd,$query);
mysqli_close($conexionbd);
$registro = mysqli_fetch_assoc($resultado);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Modificar Empleado</title>
</head>
<body>
<form action="actualizarempleado.php" method="post" name="nuevoempleado">
Nombre: <input type="text" name="empleado_nombre" value="<?php echo $registro['nombre']?>">
<br>
<br>
Edad: <input type="text" name="empleado_edad" value="<?php echo $registro['edad']?>">
<br>
<br>
<input type="hidden" name="empleado_id" value="<?php echo $registro['id']?>">
<br>
<br>
<input type="submit" name="actualizar empleado">
</form>
</body>
</html>
These are the errors in the second page:
Notice: Undefined index: empleadoID in C:\xampp\htdocs\modificarempleado.php on line 5
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\modificarempleado.php on line 8
You have 2 major problems. First, you are not using prepared statements. Second, you have a typo error in your SQL query, missing =. You can't see the errors because you have not enabled MySQLi errors.
The correct approach would look similar to this
<?php
include "basededatos.php";
// This line should go inside conectar_bd()
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conexionbd = conectar_bd();
// prepared -> bind -> execute -> get result
$query = "SELECT id,nombre,edad FROM empleado Where id=? LIMIT 1";
$stmt = $conexionbd->prepare($query);
$stmt->bind_param('i', $_GET['empleadoID']);
$stmt->execute();
$resultado = $stmt->get_result();
mysqli_close($conexionbd);
$registro = mysqli_fetch_assoc($resultado);
?>

PHP Website works fine on localhost, but not when I upload to server

So I coded my first php website that's using a mySQL database today. It works totally fine on my localhost, but when I upload it to the server via Filezilla, it doesnt.
Is it because I am still pointing to localhost in one case. If so, what should i be pointing to instead? Is there something I am completely missing? Something about exporting the mySQL database to the server? Any ideas, advice would be super appreciated!
<?php
function getConnected($host,$user,$pass,$db) {
$db = new mysqli($host, $user, $pass, $db);
return $db;
}
$db = getConnected('localhost','root','*********','msg_app');
?>
I get these errors:
Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied for user 'root'#'localhost' (using password: YES) in /home/hjaramil/public_html/tell_me/db/connect.php on line 5
Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in /home/hjaramil/public_html/tell_me/index.php on line 33
Fatal error: Call to a member function bind_param() on a non-object in /home/hjaramil/public_html/tell_me/index.php on line 34
This is my code:
<!DOCTYPE html>
<html class="no-js" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A Message For You</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link href="css/application.css" rel="stylesheet">
<link rel="shortcut icon" type="image/x-icon" href="images/favicon.ico">
<link href="//netdna.bootstrapcdn.com/font-awesome/3.1.1/css/font-awesome.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Lusitana|Open+Sans|Varela+Round|Quattrocento+Sans' rel='stylesheet' type='text/css'>
</head>
<?php
//error_reporting(0);
require 'db/connect.php';
require 'functions/security.php';
error_reporting(E_ALL);
$records = array();
if(!empty($_POST)){
if(isset($_POST['first_name'],$_POST['location'],$_POST['message'])) {
$first_name = trim($_POST['first_name']);
$location = trim($_POST['location']);
$message = trim($_POST['message']);
if(!empty($first_name) && !empty($location) && !empty($message)) {
$insert = $db -> prepare("INSERT INTO message (first_name, location, message, date) VALUES (?,?,?,NOW())");
$insert->bind_param('sss',$first_name,$location,$message);
if($insert -> execute()){
header ('Location: index.php');
die();
}
}
}
}
if($results = $db->query("SELECT * FROM message ORDER BY id DESC LIMIT 1")) {
if($results->num_rows) {
while($row = $results->fetch_object()) {
$records[] = $row;
}
$results -> free();
}
}
?>
<?php
if (!count($records)){
echo 'No messages';
} else{
?>
<?php
foreach($records as $r){
?>
<body>
<div class="msg-container">
<div class="msg-intro">
<p> I wanted to tell you that:</p>
</div>
<div class="msg-content">
<p><?php echo escape($r->message); ?></p>
</div>
<div class="msg-who">
<p class="name"><?php echo escape($r->first_name); ?></p>
<p class="location"><?php echo escape($r->location); ?></p>
<p class="date"><?php echo escape($r->date); ?></p>
</div>
<?php
}}
?>
</div>
<div class="form-background">
<div class="form-container">
<div class="form-title">
<p>What do you want to tell?</p>
</div>
<form action="index.php" method="post">
<div class="field msg">
<!--<label for="message">Message</label>-->
<textarea name="message" id="message" autocomplete="off"></textarea>
</div>
<div class="fields">
<ul>
<li> <label for="first_name">Name</label> </li>
<li> <input type="text" class="s-input" name="first_name" id="first_name" autocomplete="off"> </li>
</ul>
</div>
<div class="fields last">
<ul>
<li><label for="location">Location</label></li>
<li><input type="text" class="s-input" name="location" id="location" autocomplete="off"></li>
</ul>
</div>
<input type="submit" value="Post" id="submit-button">
</form>
<div>
</div>
</body>
<script type="text/javascript" src="js/application.js"></script>
</html>
Your problem is clearly in the MySQL credentials:
Warning: mysqli::mysqli() [mysqli.mysqli]: (28000/1045): Access denied
for user 'root'#'localhost' (using password: YES) in
/home/hjaramil/public_html/tell_me/db/connect.php on line 5
You are being denied access to the localhost MySQL server using the username of root and whatever password you have. 100% of nobody should use root on a server outside of their local desktop. And I doubt that the remote server you are using allows root access. You need to get a DB setup on the server with credentials & a database. A good chance is that it will be a localhost connection, but if not ou need that info to.
So to summarize you need the following:
Database: A database on the remote server. The name of the DB should be passed along to you.
Credentials: A username & password pair.
Hostname: Should be localhost but might not be depending on your server setup.
Get those, replace them in your script & you should be good to go.
You have to make sure that you actually set up a database via your web server that is hosting your website-there is probably some option within your hosting services website called hosting tools where this option will be. Once you set that up(you won't have to perform any sort of download of the MySQL server), you use the IP address given for the MySQL server (which will almost certainly be different than the IP for your web site) as the host. It appears that all of your errors are due to this. You also may want to change your username and password when posting examples-just to be safe!

PHP Login Script Causing Blank Page

So I'm working on a PHP/SQL login script for my website. The server is a UNIX system running Apache, and PHP is installed, that much I know for sure. I have the SQL database set up, and I have my PHP code divided into sections.
http://www.woodlandastronomy.org/login.php:
<?php
session_start();
require_once 'http://www.woodlandastronomy.org/cgi-bin/classes/membership.php';
$membership = new Membership()
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Woodland Astronomy Club Website">
<meta name="keywords" content="Woodland, Astronomy, Club, Website, Moss, Lake, Neighborhood, Astronomical, Association">
<link rel="stylesheet" href="wasmain.css">
<link rel="icon" href="http://www.woodlandastronomy.org/favicon.ico" type="image/x-icon">
<script type="text/javascript" src="script1.js"></script>
<title>Woodland Astronomy Club - Home</title>
</head>
<body>
<div id="container">
<div id="header">
<img src="IMG_9897 2 (3) copy.jpg" alt="we has a issue, sorrys!1!!!" width="100%" height="200px">
<div id="linkbar">
<p class="linkbarbutton">
<b><a class="linkbarlink" href="http://www.woodlandastronomy.org/index.html">Home</a></b>
</p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.woodlandastronomy.org/aboutus.html">About Us</a></b></p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.woodlandastronomy.org/events.html">Club Events</a></b></p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.woodlandastronomy.org/eventpix.html">Club Photos</a></b></p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.woodlandastronomy.org/astropix.html">Astrophotography</a></b></p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.weatherlink.com/user/theweathercat/" target="_blank">Weather Station</a></b></p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.woodlandastronomy.org/contact.html">Contact Us</a></b></p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.woodlandastronomy.org/links.html">External Links</a></b></p>
<p class="linkbarbutton"><b><a class="linkbarlink" href="http://www.woodlandastronomy.org/members.html">Members</a></b></p>
</div>
</div>
<div id="content">
<div id="fluffy"></div>
<div id="login">
<form method="post" action="">
<h2 class="yellowlabel">Login <small>Enter Your Credentials</small></h2>
<p class="yellowlabel">
<label for="username" >Username: </label>
<input type="text" name="username">
</p>
<p class="yellowlabel">
<label for="password">Password: </label>
<input type="password" name="pwd">
</p>
<p>
<input type="submit" id="submit" value="Login" name="submit">
</p>
</form>
<?php
if(isset($response)) echo "<h4 class='alert'>" . $response . "</h4>";
?>
</div>
</div>
</div>
</body>
</html>
then,
http://www.woodlandastronomy.org/cgi-bin/classes/membership.php:
<?php
require 'http://www.woodlandastronomy.org/cgi-bin/classes/Mysql.php';
class Membership {
function validate_user($un, $pwd) {
$mysql = New Mysql();
$ensure_credentials = $mysql->verify_Username_and_Pass($un, $pwd);
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
header("location: http://www.woodlandastronomy.org/members.html");
} else return "Please enter a correct username and password";
}
}
?>
then,
http://www.woodlandastronomy.org/cgi-bin/classes/mysql.php:
<?php
require_once 'http://www.woodlandastronomy.org/cgi-bin/classes/constants.php';
class Mysql {
private $conn;
function __construct() {
$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or
die('There was a problem connecting to the database.');
}
function verify_Username_and_Pass($un, $pwd) {
$query = "SELECT *
FROM Membership
WHERE username = ? AND password = ?
LIMIT 1";
if($stmt = this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
if($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
}
?>
and lastly,
http://www.woodlandastronomy.org/cgi-bin/classes/constants.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', '/*I didn't want to put my database credentials on the web, you understand...');
define('DB_PASSWORD', '');
define('DB_NAME', 'Member');
?>
So before, the page was entirely blank, but that was syntax errors in the include files. After I found this, I started getting error messages telling me that PHP couldn't connect to the MySQL database. After some more work, I managed to get rid of error messages altogether, but now when I click Login, it simply tries to load until the browser eventually gives the message "The connection to the server was reset."
I'm lost. My neighbor is good with PHP, but he's out of town since this afternoon, and I can't seem to figure this one out on my own.
If someone could tell me what I'm doing wrong, that would be great.
Sorry for the exceedingly long question.
Thanks, Harold
I would suggest using XDebug and/or turning on some error tracking.
ini_set('display_errors', '1');
Do you turn on error reporting?
Il will show the PHP error
error_reporting(E_ALL | E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors','1');
You can retrieve error on terminal. For example, your site is localhost/yourproject
Open Terminal (Ctl+ Alt + T)
cd /var/log/apache2
You can see error.log in this folder
tail -f error.log
Run again your site and checks log at terminal
If you specific error log with domain name, e.g error-woodlandastronom.log,
check like that tail -f error-woodlandastronom.log
Ps. You can also truck access.log like that tail -f access.log
You are saying that you are using SQL server for database.
Therefore, you can not use mysql functions. $mysql = New Mysql();
You can use mssql functions for php.
Make sure your extension=php_pdo_mssql.dll extension should be on.
You can easily check it by printing
If not, open php.ini and remove ';' from infront of ;extension=php_pdo_mssql.dll and restart the server.

mysql_close(): supplied argument is not a valid MySQL-Link

I just hosted my self-training site and now i am getting this warning. I know that I must not have had warning notifications turned on so now this is showing up. How can fix it.
You can have a look at the warning message over at this site
here is my php code
<html>
<?php
require("db_connect.php");
?>
<head>
<title>Instant Blog</title>
<link href='images/home.ico' rel='icon' type='image/vnd.microsoft.icon'/>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="postsContainer">
<?php while($row = mysql_fetch_array($result))
{
echo "<p class=\"postedText\">" . $row['post'] . "</p>";
}
$something = mysql_close($db_conn); //Warning points here.
?>
</div>
<form action="index.php" method="post">
<div class="container">
<textarea rows="10" name = "blogText" cols="150" class="blogBox"></textarea>
<input type="image" src="images/button.png" name="btnPost" value="Post" class="postButton" style="" padding-top: 2px;/>
</div>
</form>
</body>
If anyone misses out on the comments in the original post, the problem was that the variable $db_conn was wrong.
PHP.net : mysql-close
Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
You do not have to use, but $db_conn this should be $db_conn = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
From the docs
$db_conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
mysql_close($db_conn);
You are not closing $db_conn from the db_connect.php.

Updating a Database With PHP

I'm trying to update my database records with the following code but am having no luck what so ever. Anybody care to help? Thanks
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Project Sproom</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
if(!empty($_POST['username']) && !empty($_POST['email']))
{
$newusername = mysql_real_escape_string($_POST['username']);
$newemail = mysql_real_escape_string($_POST['email']);
$edit = mysql_query("UPDATE users (Username, EmailAddress) VALUES('".$newusername."', '".$newemail."') WHERE UserID=".$_SESSION['UserID']."");
// }
?>
<div id="container">
<div id="homemenu">
<ul id="navlist">
<li id="active">Home</li>
<li>Edit Profile</li>
</ul>
</div>
<div id="homemain">
<h1>Edit Profile</h1>
<p>This will be the edit profile when i have figured out how to do it...</p>
<br />
<form method="post" action="profile.php" name="editprofile" id="editprofile">
<label for="username">Username: </label> <input type="text" name="username" id="username" value="<?=$_SESSION['Username']?>"/><br />
<label for="email">E-Mail: </label> <input type="text" name="email" id="email" value="<?=$_SESSION['EmailAddress']?>"/> <br />
<input type="submit" name="editprofile" id="editprofile" value="Submit" />
</fieldset>
</form>
</div>
</div>
<?php
}
else
{
?>
<meta http-equiv="refresh" content="0;index.php">
<?php
}
?>
You're using INSERT syntax for an UPDATE query. The syntax should be like this:
UPDATE users SET Username = 'username', EmailAddress = 'email' WHERE UserID = 1;
Docs here.
You haven't connected to the MySQL database, have you?
I didn't see that in this code...
Or is that part of the included "base.php" on top of this script?
I am afraid you need fist establish a connection to a certain MySQL database before trying to update a row in a table.
Edit:
Okay, well then. Try issue the following line of code after the update:
echo "edit was " .$edit;
This is to check whether the update query was executed successfully (in which case it should echoes true) or failed (in which case it echoes false).
So at least you can tell the result of such a mysql_query.
$edit = mysql_query("UPDATE users SET Username='".$newusername."', EmailAddress='".$newemail."' WHERE UserID=".$_SESSION['UserID']."");
Try this

Categories