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

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.

Related

PHP Error Connecting to Database

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');

Very strange situation with Can't connect to local MySQL server

I'm experiencing a strange situation, and it's the first time in 5 years...
my code:
<?php include("static/inc/settings.php"); ?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>News</title>
<link rel="stylesheet" href="static/css/style.css" media="screen" />
<script type="text/javascript" src="static/js/jquery.js"></script>
<script type="text/javascript" src="static/js/tinymce.min.js"></script>
<script type="text/javascript" src="static/js/script.js"></script>
</head>
<body>
<div id="master">
<?php if(isset($_POST["inserisci"])){
$tipo=$_POST["tipo"];
$titolo=$_POST["titolo"];
$testo=$_POST["testo"];
$link=$_POST["link"];
$info=pathinfo($_FILES["immagine"]["name"]);
$ext=$info["extension"];
$newname=md5($titolo.time()).".".$ext;
$target="static/uploads/".$newname;
move_uploaded_file($_FILES['immagine']['tmp_name'],$target);
mysql_query("INSERT INTO links(url) VALUES('".$link."');") or die(mysql_error()); ?>
<div class="inserito scompari">La news รจ stata inserita</div>
<?php } ?>
<div id="header">
<?php include("static/inc/menu.php"); ?>
</div>
<div id="main">
<div class="block">
<form enctype="multipart/form-data" id="inserisci_news" method="post">
<p>Tipo<br /><select name="tipo" id="tipo"><option value=""></option><option value="sinistra">sinistra</option><option value="sopra">sopra</option></select></p>
<p>Titolo<br /><input type="text" name="titolo" id="titolo" value="ciao" /></p>
<p>Testo<br /><textarea name="testo" id="testo">prova</textarea></p>
<p>Link<br /><input type="text" name="link" id="link" value="http://www.google.it" /></p>
<p>Immagine<br /><input type="file" name="immagine" value="" /></p>
<input type="submit" name="inserisci" value="Inserisci" />
</form>
</div>
</div>
</div>
</body>
</html>
basically, when I compile the form, I get an error in the query: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
but if I remove the if(isset($_POST["inserisci"])){ cycle.... It goes!!!
What the hell?
In settings.php there's the connection:
<?php $dbname="xxx";
$user="xxx";
$pswd="xxx";
$host="xxx";
if(!isset($link)){
$link=mysql_connect($host, $user, $pswd);
if(!$link){
die('Could not connect: '.mysql_error());
}
mysql_set_charset('utf8', $link);
$db_selected=mysql_select_db($dbname, $link);
if(!$db_selected){
die('Could not use db: '.mysql_error());
}
}
date_default_timezone_set('Europe/Rome'); ?>
I think the problem is that you're doing everything with global variables and you've stomped on yourself.
The relevant line in settings.php:
$link=mysql_connect($host, $user, $pswd);
The relevant line in your code:
$link=$_POST["link"];
What you have done is overwritten the variable containing the MySQL connection with something else. This is probably resulting in your query not having a valid connection object to use. I don't know why removing the isset() conditional appears to cause the error to disappear, but I would recommend changing the name of either of these variables and seeing what happens.

PHP Simple Search Result

I'm a php newbie, and I am having issues getting a search result to return after when trying to get results from an access database. Can anyone spot any glaring issues with the following code? I want it to search the database of books (with author and title in the table) and return the author/book name. Any help is much appreciated! Thanks!
<body>
<div id="wrapper">
<div id="content">
<h1>Search for a book</h1>
<p>You may search by author or title</p>
<form method="post" action="assignment3.php" >
<input type="text" name="search">
<input type="submit" name="submit" value="Search">
</form>
<br />
<?php
if(isset($_POST['submit'])){
echo "<h2>Search Results</h2>";
$author=filter_input (INPUT_POST, 'author');
$title=filter_input (INPUT_POST, 'title');
$conn = new COM("ADODB.Connection") or die ("Cannot start ADO");
$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="assignment3.mdb"; //connect to database
$conn->open($connString);
$search_data("SELECT author, title FROM AuthorTitle WHERE author LIKE '%".$_POST['search']."%') OR title LIKE '%".$POST['search']."%'");
if(($search_data)!=0){
$rs=$searchquery;
}
?>
<?php if(($searchquery)!=0) {
do {
echo "<p>'.$author.' ',' '.$title.'</p>";
} while ($rs=($searchquery));
}
else {
echo "No results.";
}
}//end if
?>
</div> <!--end content-->
</div> <!--end wrapper-->
</body>
</html>
First thing is that You are not enclosing the brackets properly. Try Changing
$search_data("SELECT author, title FROM AuthorTitle WHERE author LIKE '%".$_POST['search']."%') OR title LIKE '%".$POST['search']."%'");
this to
$search_data("SELECT author, title FROM AuthorTitle WHERE author LIKE '%".$_POST['search']."%' OR title LIKE '%".$POST['search']."%'");
And the other thing is that you are not using quotes properly. Change
$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="assignment3.mdb";
this to
$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='assignment3.mdb'";
Hope this helps you
Folks - this is the code I used to get it to work:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Book Search</title>
<link href="assignment2.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="content">
<h1>Search for a book</h1>
<p>You may search by author or title</p>
<form method="post" action="" >
<input type="text" name="search">
<input type="submit" name="submit" value="Search">
</form>
<br />
<?php
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$connString= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\\assignment3.mdb";
//creates the connection object and define the connection string
$conn->Open($connString);
$searchquery = filter_input(INPUT_POST, 'search');
$selectCommand="SELECT * FROM AuthorTitle WHERE title LIKE '%$searchquery%' OR author LIKE '%$searchquery%'";
if(isset($_POST['search'])){
$rs = $conn->Execute($selectCommand);
//opens a recordset from the connection object
if (!$rs->EOF){
$selectCommand=$rs->Fields("ProductID");
$author=$rs->Fields("author");
$title=$rs->Fields("title");
echo "<h1>Search Result for '<b>$searchquery</b>':</h1>
<p><b>$title</b>, $author is available for checkout.</p><br />";
}
else
print "No results found.<br /><br />";
$rs->Close;
}
?>
</div> <!--end content-->
</div> <!--end wrapper-->
</body>
</html>

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.

Categories