Form submission giving me a server error - php

I've tried looking for the problem but I can't seem to figure it out. The form shows with no errors, but on google chrome it just says "Server Error" when I try and submit the form.
<?php
if (empty($_GET["entries"])) //check if the admin entered # of weeks
{
?>
<p>How many weeks do you want to make? </p>
<form action="" method="get">
<input type="text" name="entries" placeholder="Number of weeks" />
<br/>
<input type="submit" name="submit_entries" />
</form>
<?php
}
else
{
//Second form
if (isset($_POST["submit"])) //check if submitted
{
//Process form
$entries=$_GET['entries'];
$newWeeks=$_POST['week'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$sql = "INSERT INTO onlineformdata (numberOfWeeks, newCampSessions) VALUES (" . PrepSQL($entries) . "," . PrepSQL($newWeeks) . ")";
mysql_query($sql);
if (mysql_query($sql) === FALSE) {
die(mysql_error());
}
mysql_close();
}
else //if not submitted yet, show the form
{
echo '<form action="" method="post">';
for ($count = 0; $count < $_GET["entries"]; $count++)
{
echo 'Enter a beginning to ending date for the week: <input type="text" name="week"><br/>';
}
echo '<input type="submit" name="submit"></form>';
}
}
?>
Maybe it's because I can't have the first form having an action pointing to itself (Where I'm using a method="get".

You don't appear to have defined the PrepSQL() anywhere. If that's the case you should be getting a fatal error, something like
Fatal error: Call to undefined function PrepSQL ...
Once that's fixed, if you're insert query is failing, it will probably be because of the values lacking enclosing quotes.
For future debugging you can turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Or you can just observe your server's error log. How that is done depends on the server setup so I suggest asking your host for directions.
Side note:
The mysql_* library is deprecated, consider upgrading to PDO or MySQLi
The use of a Prepared Statement is preferred to concatenating variables into your SQL.

Related

Assistance with prepare statement

Edit: Error: Column count doesn't match value count at row 1
I have been trying for a long time now (hours if not days with multiple attempts) to set up a prepared statement to stop SQL injection attacks and I just cannot get my head around it. Could someone help me out with this and point out where I have went wrong? I want to learn how to do this so I can use it in future but at this rate I will never get it.
The form:
<form action="php/xaddPlayerSkills.php" method="post"> <!--player skills form to be added-->
playerID : <input type="int" name="playerID" value="<?php echo $playerID ?>" readonly> </td></tr>
SquadID: <input type="text" name="squadID"><br>
Passing: <input type="text" name="passing" value="Standard: Spin: Pop:"><br>
Tackling: <input type="text" name="tackling" value="Front: Rear: Side: Scrabble:"><br>
Kicking: <input type="text" name="kicking" value="Drop: Punt: Grubber: Goal:"><br>
Comments: <input type="text" name="comments"><br>
Date: <input type="date" name="date"><br>
<input type="Submit" value = "Add ">
</form>
This is my processing page:
<?php session_start(); include('functions.php');
$sheetNo="";
$playerID=$_POST['playerID'];
$squadID=$_POST['squadID'];
$passing=$_POST['passing'];
$kicking=$_POST['kicking'];
$tackling=$_POST['tackling'];
$comments=$_POST['comments'];
$date=$_POST['date'];
/* Use for error testing - Uncomment to check variable values when executed
ini_set('display_errors', 'On'); ini_set('html_errors', 0); error_reporting(-1);
print_r($_POST); */
//sets up and executes the connection using the information held above
/* THERE IS CONNECTION INFORMATION HERE BUT I HAVE REMOVED IT AS IT IS CREDENTIALS */
$con=mysqli_connect($host,$user,$userpass,$schema);
// Error handling: If connection fails, the next lines of code will error handle the problem and if possible, give a reason why.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= mysqli_query($con,"INSERT INTO playerSkills VALUES (playerID,squadID,passing,tackling,kicking,comments,date)");
$insert=$con->prepare($result);
$insert->bind_param("isssssd",$playerID,$squadID,$passing,$tackling,$kicking,$comments,$date);
$insert->execute();
$insert->close();
mysqli_close($con);
header ("location: ../databasePlayers.php");
?>
You have a couple of problems in your code, but the most notable is the placeholders in the query, which should ?'s instead of things like VALUES (playerID,squadID,passing,tackling,kicking... and that you're using a type double, d, to describe a date:
$con=mysqli_connect($host,$user,$userpass,$schema);
// Error handling: If connection fails, the next lines of code will error handle the problem and if possible, give a reason why.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result= "INSERT INTO playerSkills VALUES (?,?,?,?,?,?,?)";
$insert=$con->prepare($result);
$insert->bind_param("issssss",$playerID,$squadID,$passing,$tackling,$kicking,$comments,$date); // change d to s for the date
$insert->execute();
$insert->close();
Read the docs for clarification on the data types. d is for doubles, not dates. Then look at the examples for what you should use as placeholders.
EDIT: Caution - if one of these columns is an AUTO INCREMENT column you should not include it in the query as the database will take care of making sure the column is updated properly.

No results displayed when querying database

I'm trying to create a searchable database using PHP and MySQL. I have a file called mission.html with the following code:
<html>
<body>
<form name="form1" method="post" action="mission1results.php" id="search">
<input name="search" type="text"/>
<input type="submit" name="submit" vaule="Search"/>
</form>
mission1results.php
<html>
<body>
<?php
include 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
if(mysqli_connect_error()){
die("Database Connection Failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
$q_cond = mysqli_real_escape_string($_GET['search']);
$query="SELECT * From Merchant Where MerchantName='".$q_cond."'";
$result=mysqli_query($connection,$query);
if ($result===false)
{
die("Database Query Failed!")
};
while ($row=mysqli_fetch_assoc($result)){
echo "MerchantName: ".$row["MerchantName"].",";
echo "<hr/>";
}
mysqli_free_result($result);
?>
<?php
mysqli_close($connection);
?>
</body>
</html>
When I hit submit and type in anything in the searchbar nothing appears. I don't get an error, I don't get results, its all blank. Can anyone tell me why this is?
You have a syntax error in mission1results.php
if ($result===false)
{
die("Database Query Failed!")
};
must be changed for:
if ($result===false)
{
die("Database Query Failed!");
}
Instead $_GET['search'] use $_POST['search'] because your submit forms method is post.
One of mysqli_real_escape_string parameters should be DB connection.
syntax errors in HTML, for example, vaule="Search"
syntax errors in PHP, for example, there shoudn't be ; after } in if
If you are getting a blank screen with the errors pointed out in previous answers you might want to take a look at the PHP error_reporting level on your system http://php.net/manual/en/function.error-reporting.php. You should be seeing PHP errors, on a development server I like to report PHP errors, warnings and notices.
Also, are you expecting users to enter an exact search term? You might want to consider something like:
$query="SELECT * From `Merchant` Where `MerchantName` like '%".$q_cond."%'";
First and foremost: mysqli_real_escape_string() requires a DB connection be passed, then there is your form where you are using a POST method in the form and GET for your query.
Consult the manual: http://php.net/manual/en/mysqli.real-escape-string.php
$q_cond = mysqli_real_escape_string($connection,$_POST['search']);
Plus, change
if ($result===false)
{
die("Database Query Failed!")
};
to
if ($result===false)
{
die("Database Query Failed!");
}
You also have a syntax error vaule="Search" change it to value
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Also or die(mysqli_error($connection)) to mysqli_query() to find any possible errors.

can't insert data in a mysql database using php

first of all i am pretty new with mysql and php and for now i just want to insert some data in a mysql database form two text box using php.
here the database name is "info" and table name is "students" having three columns like id(primary key, auto increment activated), name and dept. There are two text boxes txtName and txtDept. I want that when i press the enter button the data form the text boxes will be inserted into the mysql database. I have tried the following code but data is not being inserted in the table....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
There are a few things wrong with your posted code.
mehtod="post" it should be method="post" - typo.
Plus, quote your VALUES
VALUES('$name','$dept')
DO use prepared statements, or PDO with prepared statements.
because your present code is open to SQL injection
and add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
You should also check for DB errors.
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
as well as or die(mysqli_error($con)) to mysqli_query()
Sidenote/suggestion:
If your entire code is inside the same file (which appears to be), consider wrapping your PHP/SQL inside a conditional statement using the submit button named attribute, otherwise, you may get an Undefined index... warning.
Naming your submit button <input type="submit" name="submit" value="Enter"/>
and doing
if(isset($_POST['submit'])){ code to execute }
Just doing if($_POST){ may give unexpected results when error reporting is set.
Rewrite: with some added security using mysqli_real_escape_string() and stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
As per the manual: http://php.net/manual/en/mysqli.connect-error.php and if you wish to use the following method where a comment has been given to that effect:
<?php
$link = #mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
God save us all...
Use PDO class instead :). By using PDO you can additionally make prepared statement on client side and use named parameters. More over if you ever have to change your database driver PDO support around 12 different drivers (eighteen different databases!) where MySQLi supports only one driver (MySQL). :(
In term of performance MySQLi is around 2,5% faster however this is not a big difference at all. My choice is PDO anyway :).

PHP code not inserting data into MySQL Database

Basically i've been scratching my head at this and I still can't figure out why it's not inserting.
I'm 100% sure the database is connected as it's fetching information just fine, however the following code fails to insert anything into the database. I've checked for spelling mistakes, i've checked from deprecated php code etc, and have used mysqli and mysql.
<?php
include_once "settings.php";
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset($_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
?>
<form method="POST">
<div class="searchContain">
<input name="textfield" type="text" name="messageTo" class="input search"><br />
<textarea placeholder="Your message..." name="messageBody" class="input sendmsg" ></textarea><br />
<button class="input" name="sendMessage">Send Message</button>
</div>
</form>
Settings.php:
<?php
session_start();
include_once "../more/config/connect.php";
// Settings //
function logincheck(){
if (!isset($_SESSION['username'])){
header("location: ../index.php");
}
}
logincheck();
$username=$_SESSION['username'];
$gatherInfo=mysql_query("SELECT * FROM users WHERE username='$username' LIMIT 1");
$fetch=mysql_fetch_object($gatherInfo);
?>
connect.php:
<?php
// Connect to the server //
date_default_timezone_set('Europe/London');
mysql_connect("localhost", "root", "connected") or die (mysql_error ());
mysql_select_db("ts") or die(mysql_error());
?>
If anyone could help me fix this rather basic rookie error I'd be very grateful!
UPDATE:
Basically after changing the code. I've gone through the MAMP panel and changed the errors so they display. It's giving me the following error message:
Warning: mysql_connect(): Can't connect to local MySQL server through socket '/Applications/MAMP/tmp/mysql/mysql.sock' (2)
in I've never come across this error before, any ideas? It seems to fetch data from the database just fine, so I'm not sure why.
try changing your query to
$query= "INSERT INTO `inbox` (`msgTo`, `msgFrom`, `msgBody`)
VALUES('$messageTo', '$username', '$messageBody')";
you can try the following
if (isset($_POST['sendMessage']) && isset($_POST['messageTo']) && isset$_POST['messageBody'])){
$messageTo = mysql_real_escape_string($_POST['messageTo']);
$messageBody = mysql_real_escape_string($_POST['messageBody']);
$query= "INSERT INTO inbox ('msgTo', 'msgFrom', 'msgBody')
VALUES('$messageTo', '$username', '$messageBody')";
if(mysql_query($query))
echo "done.";
else
echo "Problem with Query";
}
Column names should be in single inverted commas
You should check for the mysql_query to give success response.
do not call the same function again and again i.e mysql_real_escape_string was called 2 times for the same thing. Alternatively assign that to a variable, although you need not have escaped the values to check in if condition

how to call php variables outside php tags

i want to call $query somewhere inside the html and this returns undefined. Even after declaring the variable as GLOBAL i still get that error.
<?php
if($query){
echo "Nice";
}
else {
echo "Bad";
}
?>
The Full PHP
<?php
if(isset($_POST["Name"])) {
$con = mysql_connect("localhost","root","pwd", "DB");
if (!$con){
die(mysql_error());
}
$db_selected = mysql_select_db("DB", $con) or die (mysql_error());
$Name = preg_replace ('#[^a-z, 1-9 ]#i', '', $_POST['Name']);
$Slog = preg_replace ('#[^a-z ]#i', '', $_POST['Slog']);
$GLOBAL['query'] = mysql_query("INSERT INTO profiles (Name, Slog)
VALUES('$Name', '$Slog')") or die (mysql_error());
mysql_close($con);
}
?>
Here's the html with php and the $query im calling.
<form style="width:100px" action="insert.php" method="post">
<input type="text" name="Name">
<input type="text" name="Slog">
<input type="submit">
</form>
<p>
<?php
if($query){
echo "Nice";
}
else {
echo "Bad";
}
?>
</p>
are your php tags and html file located on the same document? if not. then you need to include your php file together your html codes. in .php filetype.
edit: I see a problem. you're saying "or die()" so if there's an error, it will STOP the script. if you don't want that , then you can echo the error instead of die. die will stop everything, so then query won't be defined. specifically, if the query returns false, then the "or die" happens before anything gets assigned to query.
what are you expecting query to be? it's an insert query so it should be true or false. but it has to be in the same file with the html, and what you posted is clearly not the full html.
first, try adding $con, as the second parameter of your query, eg "insert ....",$con) then, ensure you're actually getting that name parameter in the post, by adding an else or something.

Categories