Assistance with prepare statement - php

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.

Related

Info does not submit into database

We have an assignment for school and I've tried to build the application, however some text that I want to have inserted into a database doesn't get submitted.
I've tried different things, but the page does not show an error either.
This is the code of my insert page
<head>
</head>
<body>
<form action="index.php" method="post">
ID: <input type="text" name="id"><br/>
Server: <input type="text" name="Server"><br/>
Student: <input type="text" name="Student"><br/>
Docent: <input type="text" name="Docent"><br/>
Project: <input type="text" name="Project"><br/>
Startdatum: <input type="text" name="Startdatum"><br/>
Einddatum: <input type="text" name="Einddatum"><br/>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$con = mysqli_connect("localhost", "root", "usbw", "serverruimte");
if(!$con) {
die(mysqli_connect_error());
}
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
$result = mysqli_query($con, $sql);
if($result) {
echo "Opslaan voltooid!";
} else {
echo mysqli_error($con);
}
mysqli_close($con);
}
?>
</body>
</html>
Basically, what happens is: https://i.imgur.com/aUOx5yj.mp4
Does anyone know what the problem is and why the inserted data does not show up on the index page? The data does show on the page when I submit it directly into the MYSQL database.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
When working with MySQLi you should enable automatic error reporting instead of checking for errors manually. Checking for errors manually is a terrible practice, very error prone and should be avoided at all costs. Let MySQLi throw exceptions and do not catch them. See How to get the error message in MySQLi?
When opening MySQLi connection you must specify the correct charset. The recommended one is utf8mb4.
if (isset($_POST['submit'])) {
// Enable automatic error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create new instance of MySQLi class
$con = new mysqli("localhost", "root", "usbw", "serverruimte");
// Set correct charset. Important!
$con->set_charset('utf8mb4');
$stmt = $con->prepare('INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST['id'], $_POST['Server'], $_POST['Student'], $_POST['Docent'], $_POST['Project'], $_POST['startdatum'], $_POST['einddatum']);
$stmt->execute();
echo "Opslaan voltooid!";
mysqli_close($con);
}
Change this line:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
to:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('".$_POST['id']."','".$_POST['Server']."','".$_POST[Student]."','".$_POST['Docent']."','".$_POST['Project']."','".$_POST['Startdatum']."','".$_POST['Einddatum']."')";
Reason behind this change is because your query is wrong for the following reasons:
You were using strings instead of concatenating your real values coming from $_POST
Some of your indexes in $_POST were misspelled. For example:
$_POST[einddatum] should be $_POST['Einddatum']
Also, consider that this code is vulnerable to SQL Injection

SQL Injection don't work

I was checking my webpages for SQL Injection, when the main pages didn't responded to it, I created a test script:
<?
$a = $_POST["a"];
$username="...";
$password="...";
$database="...";
mysql_connect ('...',$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$ress=mysql_query("SELECT username FROM userinfo WHERE id='$a'");
$row = mysql_fetch_array($ress);
print $row[0];
?>
<form name="form" action="hackMe.php" method="POST">
<input id="a" name="a" size="150">
<input name="Submit" type="submit" value="Submit">
</form>
But when I try this line:
'; UPDATE userinfo SET email = 'steve#unixwiz.net' WHERE email = 'testusr#gmail.com
I just get an error, and no change in the database.
Any ideas why?
Quote from the manual:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified
Highlighting by me. mysql_query() only allows a single query query per call, the second query behind the ; is ignored.
To test SQL injection you have to use a query that doesn't need a second one to do harm.
Edit:
It IS possible to allow multiple queries, but you have to explicitly state this in the mysql_connect() call.
mysql_connect($host, $username, $password, false, 65536);
// defined by MySQL:
// #define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */

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 :).

Execute PHP Script using HTML Form

Hello dear why i always fail to learning php, would be grateful if someone can help me. :'(
i was followed step by step here :
http://www.w3schools.com/php/php_mysql_insert.asp
but when i click button submit query nothing happen, just show a blank white screen and i dont see new data on database?
<html>
<body>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
<?php
$con=mysqli_connect("localhost","root","","garutexpress");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
if data successfull added it should give
echo "1 record added"; but i never see this message.
Your table name is "persons", not "Persons"
When you make a query, your table name has to be the same as in your database. If you look in phpMyAdmin , your table is "persons" with lowercase
Edited according to :
#I Can Has Cheezburger
Please change the name of your table in your code like and make sure about to wrap quotes accordingly :
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql='INSERT INTO persons (Firstname, Lastname, Age)
VALUES
("'.$_POST['firstname'].'","'.$_POST['lastname'].'","'.$_POST['age'].'");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Common error, you are not wrapping your POST array index with quotes.
Do it like:
$sql='INSERT INTO persons (FirstName, LastName, Age)
VALUES
("'.mysqli_real_escape_string($con,$_POST['firstname']).'","'.mysqli_real_escape_string($con,$_POST['lastname']).'","'.mysqli_real_escape_string($con,$_POST['age']).'");
Also, as #seblaze mentioned, table names are case-sensitive, so use persons instead of Persons
For more security, use prepared statements.
A blank screen means most of the time that you are dealing with some error. You have to turn error reporting on for your local development.
How do I enable error reporting in PHP?
Check that your column names are written camelCase in your script but not in your database.
In most cases it's handy to have an ID column which is your unique identifier.
Good practice: Start using PDO
First,
You need to update the PHP configurations as:
memory_limit = 64M
Make sure you increase the memory .
Then, you need to enable Error reporting, using .htaccess file or configure it with php.ini. Read this for help
After that you can debug your work.
Try the code in this,
http://www.tizag.com/mysqlTutorial/mysqlinsert.php
in w3schools it uses mysqli I also had some issues with it.
in the link it has some sample codes and it uses mysql

Form submission giving me a server error

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.

Categories