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

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.

Related

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>

POST Issue with PHP

I have tried putting together a basic jQuery Mobile page that connects to another file on the same path of the server to send the data. I have tested the PHP by itself in the commented out part of code.
The PHP File - submit harvest.php
$dbConnection = mysqli_connect('*********', '*********', '*********', '*********');
/*
$variety = "Aji Limon";
$picked = "11";
$weight = "22";
*/
$variety = $_POST['variety'];
$picked = $_POST['picked'];
$weight = $_POST['weight'];
$query = "INSERT INTO `harvest` (`variety`, `picked`, `weight`) VALUES ('$variety', '$picked', '$weight')";
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
?>
And the html file - index.html
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<!--Mobile Device Scaling -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
</head>
<body>
<div data-role="page" id="harvest">
<div data-role="header" data-theme="b">
<h1>Chilli Harvest</h1>
</div>
<div data-role="content">
<form name="harvest" action="submitharvest.php" method="post" data-ajax="false">
<div data-role="fieldcontain">
<label for="variety" class="select" >Variety:</label>
<select name="variety" id="variety" data-theme="b">
<option value="7 Pot Red">7 Pot Red</option>
<option value="7 Pot Yellow">7 Pot Yellow</option>
<option value="Aji Limon">Aji Limon</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="picked">Qty Picked:</label>
<input type="range" name="picked" id="picked" value="1" min="0" max="200" step="1" data-theme="b" data-track-theme="c"/>
</div>
<div data-role="fieldcontain">
<label for="weight">Weight (g):</label>
<input type="number" name="weight" id="weight" value="" data-theme="b" />
</div>
<div data-role="fieldcontain">
<input type="submit" value="Send" id="submit">
</div>
</form>
</div>
</div>
</body>
</html>
Having added the data-ajax="false" and even removing the entire query mobile framework I get the same problem of the php stating "Error Occurred" with no extra detail following it, I can't see anything going wring in the console either. Hopefully I'mm missing something very basic here? Please help.
So having tried a few things from the first couple of comments below - would it also be that the dbconnection being the culprit? I am using a NAS drive with personal MySQL database on it, do I need to speify the port number at the end? Currently I have:
$dbConnection = mysqli_connect('home IP Address:3306', 'username', 'password', 'databasename');
I have seen some connection strings like this where port numbers are involved:
$dbConnection = mysqli_connect('home IP Address', 'username', 'password', 'database name', 3306);
Which really adds to my confusion as I have tried all of the above and even putting the port number in "3306"... Stumped, anyone got any further ideas please?
Turns out after many hours of wasting time the web server that it was hosted on was blocking the MySQL via it's Firewall, so all my check were ok but the web host firewall was to blame and the web company have added an exclusion to allow this to work!

Unable to insert data into database using PHP and J Query Mobile

I can insert data into the database for the several time before this. I'm using web matrix and XAMPP to develop. I have problem while dealing with ports but then after altering something it become okay, but the database does not receive data anymore. My other system using PHP that was been develop is running good but the problem is with the jQuery mobile.
This is the index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header" data-position="fixed">
<h3>
Student Uitm
</h3>
</div>
<div data-role="content">
<form action="http://localhost/student/save2db.php" method="post">
<label>Nama</label><input type="text" name="Nama">
<label>No Kad Pengenalan</label><input type="text" maxlength="12" name="icno">
<label>Jantina</label><select name="jantina">
<option value="L">Lelaki</option>
<option value="P">Perempuan</option>
</select>
<input name="sbt" type="submit" value="save" data-inline="true">
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>
Footer
</h3>
</div>
</div>
</body>
</html>
and this is the save2db.php file:
<?php
$con=mysqli_connect("localhost","root"," ","student");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO student1 (Nama, icno, jantina)
VALUES
('$_POST[Nama]','$_POST[icno]','$_POST[jantina]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
The problems:
you check for the db connection, but you let the script run through even when it's failed
you are not being cautious enough with the received data
you don't log errors
internal problem symptoms leak out to users
Here's a possible alternative to your script taking care of these issues:
<?php
$con = mysqli_connect("localhost","root"," ","student");
// Check connection
if (mysqli_connect_errno()) {
trigger_error("Failed to connect to MySQL: " . mysqli_connect_error(),
E_USER_ERROR);
die("unable to complete request");
} else if (!(isset($_POST['Nama']) &&
isset($_POST['icno']) && isset($_POST['jantina'])) {
trigger_error( "incomplete POST data", E_USER_ERROR);
die("unable to complete request");
} else {
$nama = mysqli_real_escape_string($con, $_POST['Nama']);
$icno = mysqli_real_escape_string($con $_POST['icno']);
$jantina = mysqli_real_escape_string($con,$_POST['jantina']);
$sql = "INSERT INTO student1 (Nama, icno, jantina) VALUES ('$nama','$icno','$jantina')";
if (!mysqli_query($con,$sql)) {
trigger_error("query failed :" . mysqli_error($con), E_USER_ERROR);
die("unable to complete request");
}
echo "1 record added";
mysqli_close($con);
}
With the above modification done, check the php logs after unsuccessful updates to know the possible reasons of the failure.

my jquery mobile is not working with my php code

Below is my code(jquery mobile and php) I am trying to insert into the database and also echo the following message (pls fill all field and registration complete) that is if the user complete the field or not the following message show display but non of it is working with my jquery mobile code and it is working with my normal site how can I fix this I will appreciate it if you work on my code thank you
<?php
$db= “user”;
$connect = mysql_connect(“localhost“, “alluser”, “six4”)or die(“could not connect”);
Mysql_select_db($db) or die (“could not select database”);
If (isset($_POST['submit'])){
If(empty($_POST['name']) OR empty($_POST['email']) OR empty($_POST['add'])){
$msg = 'pls fill all field';
$name = ($_POST['name']);
$email = ($_POST['email']);
$address = ($_POST['add']);
mysql_query(“INSERT INTO people (Name, Email, Address”) VALUES ('$name, $email, $address')”) or die (mysql_error());
$msg='registration complete ';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="css/jquery.mobile-1.0a1.min.css" />
<script src="js/jquery-1.4.3.min.js"></script>
<script src="js/jquery.mobile-1.0a1.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>User</h1>
</div>
<div data-role="content">
<?php echo “$msg”; ?>
<form name=“form” action=“” method=“post”>
<label for=“name”>Name</label>
<input type=“text” name=“name” />
<label for=“email”>Email</label>
<input type=“text” name=“email” />
<label for=“address”>Address</label>
<input type=“text” name=“add” />
<input type=“submit” name=“submit” value=“Submit” />
</form>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
Check your brace positions after your if statements. You check for empty values, but you don't alter the program flow in a meaningful way if you find them.
Also, replace your curly quotes with real quotes. And check for SQL injection. And double-check your MySQL call. You'll get an error from PHP before you'll ever get $msg echoed, based on the way things are written.

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.

Categories