Problem with PHP Page connecting to DB - php

<?php
$dbserver="localhost";
$username="root";
$pass="root";
$link=mysql_connect("$dbserver","$username","$pass");
if(!$link){die('DB Connection Failed'.mysql_error()); }
echo('connected');
$Name=$_POST["namei"];
$ID=$_POST["pid"];
$Address=$_POST["address"];
$Phone=$_POST["phone"];
$query="INSERT INTO contact(Name,ID,Address,Phone) VALUES('".$Name."',".$ID.",'".$Address."',".$Phone.");";
echo($query);
?>
The code above is used by me to connect to a mysql db, i'm posting the contents to this page from an html page. As i checked there is no problem with POST. but on click of submit it gives me an error '500 Internal Server Error'.
I'm using Apache 2.2 Server, and mysql 5.5.
Can any one tell what is my mistake?
Thank you

First please run
<?php
echo 'phpversion: ', phpversion(), "<br />\n";
if ( !extension_loaded('mysql') ) {
die('mysql module not available');
}
echo 'mysql_get_client_info: ', mysql_get_client_info(), "<br />\n";
die;
to check whether a) you can run any php script and b) the mysql_* functions are available.
Then try
<?php
echo "start<br />\n";
error_reporting(E_ALL);
ini_set('display_errors', true);
flush();
$dbserver="localhost";
$username="root";
$pass="root";
$link=mysql_connect($dbserver, $username, $pass);
if(!$link) {
die('DB Connection Failed '.mysql_error());
}
echo "connected<br />\n";
if ( !mysql_select_db('dbname here', $link) ) {
die('DB selection failed. '.mysql_error($link));
}
echo "db selected<br />\n";
$Name = mysql_real_escape_string($_POST['namei'], $link);
$ID = mysql_real_escape_string($_POST['pid'], $link);
$Address = mysql_real_escape_string($_POST['address'], $link);
$Phone = mysql_real_escape_string($_POST['phone'], $link);
$query = "
INSERT INTO
contact
(Name,ID,Address,Phone)
VALUES
('$Name', '$ID','$Address','$Phone')
";
echo '<pre>Debug: query=', htmlentities($query), "</pre>\n";
It prints something in any case (echo/flush) and sets error_reporting + display_errors so that error messages are sent to the client (you don't want that in production, don't forget to remove those lines).
I also added the necessary calls to mysql_select_db() and mysql_real_escape_string() (needed as soon as the script really sends the query to the mysql server).

K,
You should add
ini_set('display_errors', 1);
error_reporting(E_ALL);
To the beginning of your script. This will stop the 500 errors and give you the proper error message so you have a better idea of what is going wrong.
It might be the echo($query); line, you only need echo $query; without the parentheses.

Related

PHP mysql no error but keeps failing

I have no idea what's going on. I usually have simple sign in pages like this done very quickly but this one isn't working and I cannot spot the error.
<?php
$con=mysql_connect("db_server","db_user","db_pass","db");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$query="SELECT username FROM users ";
//$query.="WHERE `username`=".$username;
//$query.=" AND `password`=".$password;
echo "query=".$query."<br/>";
$result = mysql_query($query, $con);
echo "result=".$result."<br/>";
if($result){
$row = mysql_fetch_assoc($result);
$data = $row['username'];
echo "data=".$data;
}else{
echo "something went wrong:".mysql_error();
}
mysql_close($con);
?>
im using mysql_* instead of mysqli_* as the server im running it on is 5.2; not sure if that is relevant but I was getting an unrecognized function error originally.
There is only one entry in the database. As I said, I use the regular SQL code through phpmyadmin and i get the results i need.
Also not sure if relevant. I'm echoing $result and nothing comes out. Isnt it supposed to echo "false"?
You have a major error in your logic, for one. If there is an error connecting to MySQL, you print the error, but yet proceed to query the broken connection - you are also not selecting a database.
Also, this approach is for PHP4. Unless you are stuck in PHP4 on this project, moving into the PHP5 world would be a good idea.
I recommend looking into PDO:
http://www.php.net/manual/en/book.pdo.php
As for not getting errors, check your error_reporting and display_errors settings in your .ini
Try this one.
<?php
$con=mysql_connect("db_server","db_user","db_pass");
mysql_select_db("db");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysql_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$query=mysql_query("SELECT username FROM users");
if($query){
$row = mysql_fetch_assoc($query);
$data = $row['username'];
echo $data;
}else{
echo "something went wrong:".mysql_error();
}
mysql_close($con);
?>

Header, logic and database

I am having an issue with my header location. I am new to php and I am unable to redirect to my index page after this separate php file is run. In addition my function is unable to tell whether the contents of a text box is blank or equal to the default value of "<>".
Thank you
<?php
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
{
// the form was submitted
//remove hacker HTML
$email2=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email2'";
$result=mysql_query($sql2);
//Direct back to homepage
echo "heloooo";
header('location:/index.php');
}
else
{
header('location:/index.php');
}
}
else
{
header('Location:http://www.google.com');
`enter code here`}
?>
EDIT
After making the changes suggested my error log is as follows
Notice: Use of undefined constant db_selected - assumed 'db_selected' in /home/clubbtpk/public_html/connectionFile.php on line 15
Warning: Cannot modify header information - headers already sent by (output started at /home/clubbtpk/public_html/connectionFile.php:15) in /home/clubbtpk/public_html/addEmail.php on line 28
The code in the connection file is:
<?php
$host="localhost";
$username="username";
$password ="password";
// Create connection to mysql server
$con=mysql_connect("$host","$username","$password");
// Check connection
if (!$con)
{
die ("Failed to connect to MySQL: " . mysql_error());
}
// Select database
$db_selected = mysql_select_db("DB", $con);
if(!db_selected)
{
die ("Cannot connect : " . mysql_error());
}
?>
EDIT 2
Resolved first error by changing
if(!db_selected)
to
if(!$db_selected)
RESOLVED
Added the following line of code to my index.php file:
<?php
if(isset($_REQUEST["emailAdd"])){
include("addEmail.php");
}
?>
Then changed the action of the form to "" so that it reloads the current page:
<form name="emailAddr" method="post" action="">
You must not output anything before your redirect.
So this is not allowed:
echo "heloooo";
header('location:/index.php');
EDIT: You should definitely enable error_reporting on your script. I found another error in your query:
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '$_POST[emailAdd]'";
should be
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
Furthermore you should not use the mysql_* functions anymore but upgrade to mysqli_* functions. And always check the inputted data before inserting them into sql-queries.
EDIT2: Add this at the beginning of your script:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
EDIT3:
You have to change this line too:
if(isset($_POST['emailAdd']) && !empty($_POST['emailAdd']) && $_POST['emailAdd'].value != "<<please enter email>>")
Should be:
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>")
If you would turn error_reporting on you would see it yourself.

Problem in displaying and connectivity with mysql in php

I am new in php, I created a page with mysql db connectivity but when the page is run it displays a blank page. If i write a echo statement before the connection statement then only echo statement is displayed and nothing else is displayed. Here is my code..
$con = mysql_connect('localhost','root','admin');
mysql_select_db('testdb',$con);
if ($con)
{
die('Connected to database!');
}
$sql = " INSERT INTO customer ([Name],[Website]) VALUES('$_POST[fname]','$_POST[lname]') ";
$result = mysql_query($sql, $con);
if(!$result)
{
echo mysql_error();
exit;
}
// close the connection
mysql_free_result($result);
mysql_close($con);
Anyone please help why this problem occurs and is there is anything wrong in the page.
Display Errors was off. I edit in the php.ini file 'display_errors' On. But still the connectivity issue is not resolved. It displays an fatal error at connectivity line statement.
fatal error: Call to undefined function mysql_connect()
$con = mysql_connect('localhost','root','admin');
mysql_select_db('testdb',$con);
if (!$con)
{
die('Not Connected to database!');
}
$sql = " INSERT INTO customer ([Name],[Website]) VALUES('$_POST[fname]','$_POST[lname]') ";
$result = mysql_query($sql, $con);
if(!$result)
{
echo mysql_error();
exit;
}
else
{
echo 'Query Success';
}
// close the connection
mysql_free_result($result);
mysql_close($con);
As you have
die('Connected to database!');
this will stop the script here, script written after it will not be executed , use instead
echo('Connected to database!');
[Name],[Website] should be replace with Name, website
your script dies everytime it success to connect to DB
change
if ($con)
{
die('Connected to database!');
}
to
if (!$con)
{
die('Connected to database!');
}

Insert data into MySql table strange exception

I am using this code to insert some values in MySql table:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bib");
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query);
// Display an appropriate message
if ($result)
echo "<p>Product successfully inserted!</p>";
else
echo "<p>There was a problem inserting the Book!</p>";
mysql_close();
?>
After running it into browser, the following error occurs:
"Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience."
It seems that mysql_select_db("bib") statement causes it. Database is create , also table...
I am running php 5.3 and mysql 5.1 on windows xp sp 2.
Please any ideas are welcomed...
Thanks...
Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}
try this to connect to database:
$mysqlID = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Unable to connect to database");
mysql_select_db(DB_DATABASE) or die("Unable to select database ".DB_DATABASE);
also, try this as your insert query:
$query = "INSERT INTO carte (id, title) values ('".$id."', '".addslashes($titlu)."')
$result = mysql_query($query) or die(mysql_error());
By using die(), it will tell you where it has failed and why

Why it's not "if" and not "else"?

I have this code:
$link = mysql_connect("localhost", "ctmanager", "pswsafgcsadfgG");
if ( ! $link )
die("I cannot connect to MySQL.<br>\n");
else
print "Connection is established.<br>\n";
print "a";
if ( mysql_create_db("ct", $link) )
print "AAA";
else
print "BBB";
print "2";
die();
And this is the output:
Connection is established.
a
So, I cannot understand how it's possible that neither "AAA" no "BBB" is outputted. Is it because program dies at mysql_create_db?
You probably guessed right. Try adding:
error_reporting(-1);
ini_set('display_errors', 'On');
at the very top of your script. You will get more details I'm sure. Post your findings and I'll update my answer if needed to.
Also, if you use PHP 5, you can try:
try
{
if (mysql_create_db("ct", $link))
echo 'AAA';
else
echo 'BBB';
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
maybe this will catch something...
Also, as František Žiačik pointed out with his link:
The function mysql_create_db() is
deprecated. It is preferable to use
mysql_query() to issue an sql CREATE
DATABASE statement instead.
mysql_create_db is deprecated in PHP5, maybe there even does not exist anymore.
See http://php.net/manual/en/function.mysql-create-db.php for an example how to do it.
I think you're right it is failing at mysql_create_db but i would guess it's the SQL that you're passing into it. are you trying to create a DB called "ct"? If so i'd try "CREATE DATABASE ct"
What PHP version are you running? According to the documentation, mysql_create_db is depracated, and a CREATE DATABASE query should be issued instead.
if (mysql_query("CREATE DATABASE ct", $link))
print "AAA";
else
print "BBB";
I think this would be the alternate way hopefully.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
?>

Categories