Trying to display some data from mysql DB = blank page - php

<?php
//error_reporting(E_ALL); ini_set('display_errors', '1');
$connection = mysql_connect("localhost", "root", "toor");
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('test');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
session_start();
if(!isset($_SESSION['username'])){
header("Location: main.php");
}
echo "<a href='logout.php'>Logout</a>";
/*if (isset($_GET['id']){
$id = $_GET['id'];
$query = "SELECT title FROM news WHERE id=$id";
$title = mysql_query($query) or die(mysql_error());
$query = "SELECT body FROM news WHERE id=$id";
$body = mysql_query($query) or die(mysql_error());
echo "$title\n\n\n";
echo "$body\n\n";
}*/
?>
<html>
<body>
<p>
Login OK
</body>
</html>
I need to display the content of the fields title and body, however I'm getting a blank page (not even the link to logout.php is displayed). There is no error reported by error_reporting(E_ALL); ini_set('display_errors', '1');.
If I comment the if block, both the link to logout.php and the message "Login OK" are displayed.
What might be failing?
In the login.php I call news.php with:
if (isset($_SESSION['username'])){
header("Location: news.php?id=1");
}
edit
I'm noticing the call to news.php?id=1 returns an error 500.

You are using it in the wrong way
$query = "SELECT title, body FROM news WHERE id=$id";
$results = mysql_query($query);
while ($news = mysql_fetch_assoc($results)) {
echo $news["title"];
echo $news["body"];
}
the instruction mysql_query will give you a result set.
Then from results sets you have to fetch the single rows
with mysql_fetch_assoc ( or fetch_row or fetch_array, see the manual for the differencies )
Then with single result pulled you display data.
In your code i cannot see any db connection logic, there is no connection parameter passed to mysql_query function.
Error 500 means php is doing some bad error and fails to execute, anyway i would go to check the logs, the error is clearly written there and will save you headaches. /var/log/httpd/error_log generally on linux.

Related

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.

Updating mySQL data field via form not working

I'm trying to edit an item in a mySQL database generated list. Here is the code:
<?php
// contact to database
$connect = mysql_connect("<HOST>", "<USER>", "<PASSWORD>") or die ("Error , check your server connection.");
mysql_select_db("tvc");
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
$result = mysql_query("UPDATE closet SET
pattern = '{$_POST['pattern']}'
WHERE id='{$_POST['id']}'") or die ("Error in query");
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='patterns.php'>Back to Patterns List</a>";
}
else {
echo "ERROR";
}
?>
</body>
</html>
I get an 'error in query' error message and I can't figure out what is causing it.
Any help would be much appreciated!
You forgot to remove , before WHERE
Change
$result = mysql_query("UPDATE closet SET
pattern = '{$_POST['pattern']}',
WHERE id='{$_POST['id']}'") or die ("Error in query");
To
$pattern = mysql_real_escape_string($_POST['pattern']);
$id= mysql_real_escape_string($_POST['id']);
$result = mysql_query("UPDATE closet SET
pattern = '".$pattern."' WHERE id='".$id."'") or
die("Could not connect: " . mysql_error());
Recommendations:
1.Learn to prevent from MySQL Injections: Good Link
2.Mysql extension is not recommended for writing new code. Instead, either the mysqli or PDO_MySQL extension should be used. More reading: PHP Manual

Form to insert data in database works, but does not show success-page

I've a simple order-form on my website. If I click the submit-button the the form will send the data to my database. This works. But it does not show the success.php - it only shows the start.php again. So there must be a mistake. On my previous hoster it worked. But now I have a new one.
Here's my php-script (start.php):
<?php
$con = mysql_connect("localhost", "user", "pw") or die ("No connection to db possible");
mysql_select_db("db", $con) or die ("No connection to db possible");
mysql_query("SET NAMES 'utf8'");
if (isset($_POST['button']))
{
foreach ($_POST AS $key => $postvar)
$_POST[$key] = stripslashes($postvar);
$_POST['name'] = mysql_real_escape_string($_POST['name']);
$_POST['strasse'] = mysql_real_escape_string($_POST['strasse']);
$_POST['plz'] = mysql_real_escape_string($_POST['plz']);
$_POST['ort'] = mysql_real_escape_string($_POST['ort']);
$_POST['mail'] = mysql_real_escape_string($_POST['mail']);
$_POST['anzahl'] = mysql_real_escape_string($_POST['anzahl']);
$sql = "INSERT INTO `bestellungen` (`name`,`strasse`,`plz`,`ort`,`mail`,`anzahl`,`datetime`)
VALUES ('".$_POST['name']."', '".$_POST['strasse']."', '".$_POST['plz']."', '".$_POST['ort']."', '".$_POST['mail']."', '".$_POST['anzahl']."', '".date("Y-m-d H:i:s")."');";
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
?>
<?php Header("Location: success.php");
exit();
?>
<?php
} else { ?>
That won't work because header('Location: success.php') needs to happen before you output anything to the browser. You seem to have gaps before that is called.
$result = mysql_query($sql,$con);
if (!$result) echo mysql_error();
mysql_close($con);
// Now its time for the header!
header("Location: success.php");
exit();
You cannot have any output before the header() redirection.
Check your script for possible errors, warnings or notices, any of these will output text and the redirection will no happen.
So far, whenever I found this kind of problem; there must be two reasons I often do. Either I print any html code before the header function or I don't realize that my success.php also redirect to start.php.
Maybe you can check either of these two exist in your code.
Format it this way.
$result = mysql_query($sql,$con);
if (!$result) {
echo mysql_error();
} else {
Header("Location: success.php");
}
mysql_close($con);
?>

Passing variables into an included PHP file to be used as MySQL queries

I'm having trouble passing two variables into an included file.
Viewable page:
<?php
$sqlCount = "This is a working MySQL query.";
$sqlQuery = "This is also a working MySQL query.";
include("include.php");
?>
include.php:
<?php
$result = mysql_query($sqlCount, $conn) or trigger_error("SQL", E_USER_ERROR);
//$result populates variables to be used in second portion of code
//don't need $result anymore
$result = mysql_query($sqlQuery, $conn) or trigger_error("SQL", E_USER_ERROR);
//rest of my code
?>
The code works in the viewable PHP page when I don't include it. It also works when I move $sqlCount and $sqlQuery into include.php.
The only real solution I've been able to find was to declare them as global variables, but when I tried it didn't do anything.
Edit: I figured it out. $sqlQuery had variables inside the query that weren't being created until inside the include.php file.
did you try
include.php:
<?php
echo $sqlCount; die(); // just to be sure you have what you expect?
$result = mysql_query($sqlCount, $conn) or trigger_error("SQL", E_USER_ERROR);
A better approach, in my point of view would be rewriting the code in "include.php" as a function that you can then call from your "viewable page":
include.php
<?php
function included_function($sql_count, $sql_query)
{
$result = mysql_query($sql_count, $conn) or trigger_error("SQL", E_USER_ERROR);
//$result populates variables to be used in second portion of code
//don't need $result anymore
$result = mysql_query($sql_query, $conn) or trigger_error("SQL", E_USER_ERROR);
//rest of my code
}
?>
"viewable page"
<?php
include("include.php");
$sqlCount = "This is a working MySQL query.";
$sqlQuery = "This is also a working MySQL query.";
included_function($sqlCount, $sqlQuery);
?>

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

Categories