Sending Form Data to MySQL - php

I'm trying to send form data to MySQL. I've found tonnes of code on the net, so I'm copying, and pasting and creating PHP scripts and adding them to my phpAdmin, but I really have no idea.
I don't know what to add to my form as an action to tell the form to send the data to my database. I already have an action code in the form, am I able to have two?
I have created a table in my phpAdmin, but I don't know if it actually will work.
This is my PHP code that I have stuck in my public_html folder, with generic username, database name, and password. I use an IP address instead of Localhost, as this database is on the Internet through Bluehost rather than my own computer.
<?php
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$submission_id = $_POST['submission_id'];
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$homeclub = $_POST['homeclub'] ;
$course1 = $_POST['course1'] ;
$course2 = $_POST['course2'] ;
$winner = $_POST['winner'] ;
$db_host = 'localhost';
$db_username = 'userrname';
$db_password = '';
$db_name = 'dbName';
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
// search submission ID
$query = "SELECT * FROM `table_name` WHERE `submission_id` = '$submission_id'";
$sqlsearch = mysql_query($query);
$resultcount = mysql_numrows($sqlsearch);
if ($resultcount > 0) {
mysql_query("UPDATE `table_name` SET
`name` = '$name',
`email` = '$email',
`homeclub` = '$homeclub',
`course1` = '$course1',
`course2` = '$course2'
`winner` = '$winner'
WHERE `submission_id` = '$submission_id'")
or die(mysql_error());
} else {
mysql_query("INSERT INTO `table_name` (submission_id, formID, IP,
name, email, homeclub, course1, course2, winner)
VALUES ('$submission_id', '$formID', '$ip',
'$name', '$email', '$homeclub', '$course1', '$course2', '$winner') ")
or die( mysql_error());
}
?>
Any assistance will be greatly appreciated.

I'm sorry but your code is very outdated. You need to validate your value in case something is missing. I used Nulls coaling to do this (-> ?? ""), then you use mysql. You could use mysqli but I prefer and recommend PDO because it's easier. And instead to ask database if there is an insert first, just say hey update if there is an insert with the same id, or insert is (that makes Replace). But in order to do this, make submission_id unique in database
https://joshuaotwell.com/use-mysql-unique-constraint-in-phpmyadmin/
PS: this code is not tested but it should work, otherwise send me your full error report message
<?php
// read variables or assign them a default value
$submission_id = $_POST['submission_id'] ?? 0;
$name = $_POST['name'] ?? "";
$email = $_POST['email'] ?? "";
$homeclub = $_POST['homeclub'] ?? "";
$course1 = $_POST['course1'] ?? ""; // make array out of this
$course2 = $_POST['course2'] ?? "";
$winner = $_POST['winner'] ?? "";
// mysql is deprecated use pdo instead
$pdo = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_username, $db_password)
// if exists -> replace, if not exist insert (replace makes that in one query)
// submission_id must be flagged as unique in mysql otherwise it will insert a new row every time
// I use prepared statements so first tell database what to do then the value
// prevents hacking and increase secureity
$query = 'REPLACE table_name SET
name = :name
, email = :email
, homeclub = :homeclub
, course1 = :course1
, course2 = :course2
, winner = :winner
, submission_id = :submission_id';
$statement = $pdo->prepare($query);
$statement->execute(array(
':name' = $name
, ':email' = $email
, ':homeclub' = $homeclub
, ':course1' = $course1
, ':course2' = $course2
, ':winner' = $winner
, ':submission_id' = $submission_id
));

Related

Unsuccessful Updating table with PHP using Update table Set

I have a table buildtracker connected to a form. I am attempting to edit the data in a particular row and therefore Update the row.
The table consists of these columns: ID key, EnteredBy, INI
$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");
$rowID = $conn->real_escape_string($_POST['ID']);
$enteredBy = $conn->real_escape_string($_POST['enteredBy']);
$ini = $conn->real_escape_string($_POST['ini']);
$query = "UPDATE buildtracker SET
EnteredBy = '$enteredBy', INI = '$ini'
WHERE ID = '$rowID' ";
$success = $conn->query($query); //insertion above ^ is the column names
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
return $query;
I'm receiving no new data or updates on the table. What can I do differently to improve upon this?
Thanks!
I don't know in what context this code is, in your application.
But is is [highly] recommended to use prepared statements for protection against any SQL injection attacks, especially direct data from $_POST is used (can be sanitized).
Checking whether query is executed or not in prepared statements is via $stmt->execute().
$user = 'root';
$pass = '';
$db = 'cl_db';
$conn = new mysqli('localhost', $user, $pass, $db) or die("Something bad happened.");
$prepare_query = "UPDATE buildtracker SET EnteredBy=?, INI=? WHERE ID=?";
$success = $conn->query($prepare_query); //insertion above ^ is the column names
if ($stmt = $conn->prepare($query)) {
// Possible data sanitation can be done below
$rowID = ($_POST['ID']);
$enteredBy = ($_POST['enteredBy']);
$ini = ($_POST['ini']);
// bind parameters
$stmt->bind_param('ssi', $enteredBy, $ini, $rowID);
// CHECKING is here: execute query (or die)
// Can check also for ($stmt->affected_rows > 0)
if (!$stmt->execute()){
die("Couldn't enter data: ".$conn->error);
}
return $query;
}
And using PDO instead of MySQLi would probably be better recommended.
As all errors that I create - this was a result of the declaration of my $rowID not pointing the correct html element.
original
$rowID = $conn->real_escape_string($_POST['ID']); // ID is the COLUMN NAME
Working
$rowID = $conn->real_escape_string($_POST['rowID']); //rowID is the DOM element name
Thank you for your comments and answers.
Going to look into implementing Hossam's safer version of preventing injections. I appreciate you all :)

`mysql_real_escape_string()` returns empty MySql Fields

I have a HTML contact form in which the user is allowed to write whatever he wants in the message input field. This form is being posted using AJAX and being processed in the below PHP.
My problem is that i get an empty row in the MySql Table.
I am simply wondering why $message = $_POST['message']; returns the proper value, when $message = mysql_real_escape_string($_POST['message']); returns empty string!!
What am I missing here??
//posted data
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$name = $firstName. ' ' .$lastName ;
$email = mysql_real_escape_string($_POST['email']);
$phone = mysql_real_escape_string($_POST['phone']);
$subject = mysql_real_escape_string($_POST['subject']);
$hear = mysql_real_escape_string($_POST['hear']);
$message = mysql_real_escape_string($_POST['message']);
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
// Check if is Duplicates
$query_usercheck = " select * from `test` where Name='$name' and Email='$email' and Phone='$phone' and Subject='$subject' and Message='$message' "; //matching all fields
$usercheck = mysql_query($query_usercheck) or die(mysql_error());
$row_usercheck = mysql_fetch_assoc($usercheck);
$totalRows_usercheck = mysql_num_rows($usercheck);
if ( $totalRows_usercheck > 0 ) {
$duplicate = 'Yes';
} else {
$duplicate = 'No';
//adding application data to MySql database
$add = mysql_query("INSERT INTO `test` (`Date`, `Day`, `Time`, `Name`, `Email`, `Phone`, `Subject`, `From`, `Message`)
VALUES ('$date','$day','$time','$name','$email','$phone','$subject','$hear','$message')");
}
// close mysql
mysql_close();
The problem is that you connect to the database after you do mysql_real_escape_string. Please move your connecting to the database before escaping your variables.
Even better, get rid of the deprecated mysql_* functions (there are even gone in PHP7)! Use mysqli or even better: use PDO with prepared statements as even mysql_real_escape_string is not safe.
mysql_real_escape_string requires an active database connection to do its job. You have not established a connection at the point of calling it.

Dynamic array insertion into MySQL database with null

I am trying to insert multiple times an array that can have from 3 to 6 int inside it.
I created this to solve the problem:
CREATE TABLE name(
ID INT AUTO_INCREMENT NOT NULL,
NUM1 INT NOT NULL,
NUM2 INT NOT NULL,
NUM3 INT NOT NULL,
NUM4 INT,
NUM5 INT,
NUM6 INT,
PRIMARY KEY(ID)
)DEFAULT CHARSET = latin1;
On top of that I created the following code so I could insert the data. It receives $num - a int where tells how many numbers will have that aren't NULL and an array with the ints.
function inserDataBase($num,$array)
{
$x = array();
$x[0] = NULL;
$x[1] = NULL;
$x[2] = NULL;
$x[3] = NULL;
$x[4] = NULL;
$x[5] = NULL;
for($i=0;$i<$num;$i++){
$x[$i] = $array[$i];
}
//connetion to the Server
$username = "root";
$password = "";
$hostname = "localhost";
$database = "tournament";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$conn = mysql_select_db($database)
or die("Unable to connect to the selected database");
$sql = "INSERT INTO 'name' VALUES ($x[0], '$x[1]', '$x[2]', '$x[3]', '$x[4]', '$x[5]')";
mysql_query($sql,$dbhandle)
or die(mysql_error());
mysql_close($dbhandle);
}
Problems that I am getting:
I can't insert them at all. I searched a bit and I know now that SQL doesn't understand variables and I need to change that to something else but i am worried if I pass them to ints and the NULL give me some kind of trouble.
This is a inside database, I mean it is just random numbers that are going to inserted. Should I be worried about SQL injection or no?
This is a aux function so I was wondering if it was better to start the connection and close it on the end or create a single connection for each time for each insertion of data.
By putting single quotes around the inserted values, you are changing them to a string - so you won't get the record inserted.
Edit: Also, in MySQL you don't put single quotes around column names, you use a backtick ` character. I have updated all but the initial SQLs to show this.
If you change the variable in the PHP code to $x[0] = 'NULL'; you will then be able to insert a null value into a column with this:
$sql = "INSERT INTO 'name' VALUES ($x[0], $x[1], $x[2], $x[3], $x[4], $x[5])";
The code you originally had was being parsed like this:
INSERT INTO `name` VALUES (1, 2, 3, '', '', '')
Where now that the variables are being set as a string initially, the SQL will be parsed as this:
INSERT INTO `name` VALUES (1, 2, 3, null, null, null)
Edit: Having said that, I do think that one of the comments is correct, you can't parse arrays inside a string, so your code would need to look like:
$sql = "INSERT INTO `name` VALUES (".$x[0].", ".$x[1].", ".$x[2].", ".$x[3].", ".$x[4].", ".$x[5].")";
This code works. Has all the above modifications, but also includes a loop to create the sql query.
$array = array(1,2,3);
$num = count($array);
inserDataBase($num,$array);
function inserDataBase($num,$array)
{
for($i=0;$i<$num;$i++){
if $x[$i] = $array[$i];
}
for($i=$num;$num<=5;$i++){
if $x[$i] = NULL;
}
//connetion to the Server
$username = "root";
$password = "";
$hostname = "localhost";
$database = "tournament";
$dbhandle = mysqli_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$conn = mysqli_select_db($dbhandle,$database) or die("Unable to connect to the selected database");
$sql = "INSERT INTO name VALUES (''";
$count = 0;
$values = '';
for($count=0;$count<=5;$count++){
$values .= ",".$x[$count];
}
$sql .= $values . ")";
echo $sql;
mysqli_query($dbhandle,$sql) or die(mysql_error());
mysqli_close($dbhandle);
}

mysql_insert_id() always returns 0

I'm trying to retrieve the last id number inserted with mysql_insert_id() but always return 0, my id field is auto increment so I don't know why it returns 0 thanks. please help
include 'C:\xampp\htdocs\Student_evaluation\functions.php';
if(!loggedin())
{
header("Location: http://localhost/dev/userarea.php");
exit();
}
if(isset($_POST['submit']))
{
//get data
$name = $_POST['name'];
$f_lastname = $_POST['f_lastname'];
$second_lastname = $_POST['second_lastname'];
$student_number = $_POST['student_number'];
$semester_year = $_POST['semester_year'];
$course = $_POST['course'];
$section = $_POST['section'];
$grade = $_POST['grade'];
$student_perform = $_POST['student_perform'];
$comment_box = $_POST['comment_box'];
$sql = "INSERT INTO `students`(`name`, `first_lastname`, `second_lastname`, `numero_estudiante`, `semester`, `course`, `section`, `f_grade`, `students_perform`, `comments`)
VALUES ('$name','$f_lastname','$second_lastname','$student_number','$semester_year','$course','$section','$grade','$student_perform','$comment_box')";
$con = mysqli_connect("localhost","root","","rememberme");
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysql_insert_id();
}
You're using one library (mysqli) to perform the query, then another (mysql) to obtain the auto-increment ID. That can't work. Among other issues, you haven't even connected to the database with the second library!
Consistently use mysqli or, better yet, PDO, which will help you plug your blinding security flaw.
You should do something like this (using mysqli_insert_id):
$con = mysqli_connect("localhost","root","","rememberme");
$sql = "INSERT INTO ...";
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysqli_insert_id($con);
mysql_insert_id and mysqli_insert_id are both different and you are using mysqli so use mysqli_insert_id instead of mysql_insert_id and it's better to use mysqli instead of mysql.

SQL database help needed via html form and php scripts

<?php
include ("account.php") ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db($project);
$number = NULL ;
$username = $_POST["username"];
$priority = $_POST["priority"];
$category = $_POST["category"];
$incident_description = $_POST["incident_description"];
$sql = "insert into incident values ( NULL, '$username','$priority','$category','$incident_description',curdate(),curtime() )" ;
mysql_query ( $sql ) or print ( mysql_error ( ) );
$credentials = "select * from Credentials where ("username" = '$username' ,"password" = '$password' , "email_address" = 'email_address')" ;
print $credentials;
$result = mysql_query ($credentials) or print (mysql_error ( ) );
$howManyRows = mysql_num_rows ( $result);
//if $howManyRows is positive continue process to update database with sql,if not,die.
?>
There is an html code for a form on another file hence the $_POST, but I don't think it s necessary to show it here since I need the right syntaxes on this php file.
With the part from the $credentials I need help with how to compare the values in the html form (username,password,email_address) with values in the table "Credentials" from the database?I need to do this in order to authorize the values to carry on the process.
The syntax I got there isn't right at the moment because it doesn't execute it properly. I just don't know how to compare the two.
This whole thing works up until the mysql_query ( $sql ) or print ( mysql_error ( ) ) line.
Suggestions would be nice.I apologize for the long question!
PS: columns for the Credentials table are username,password,email_address as well!
the problem is here
$credentials = "select * from Credentials where ("username" = '$username' ,"password" = '$password' , "email_address" = 'email_address')" ;
change to
$credentials = "select * from Credentials where `username` = '$username' and `password` = '$password' and `email_address` = 'email_address'" ;
The problem is in query, when you want to check multiple values use AND in WHERE clause.
I dont know but shouldn't u use the following...
$sql = "INSERT INTO incident (fieldname, fieldname) VALUES ('".mysql_real_escape($_POST['fieldname'])."', '".mysql_real_escape($_POST['fieldname'])."')";
To insert anything into mysql?
You can use your credential query as below
$credentials = "select * from Credentials where username = '$username' AND password = '$password' AND email_address = 'email_address'" ;
BUT for better performance & to prevent your code for mysql injection you have to do following things
1) Use Mysqli instead of mysql functions. here is good lib for mysqli as wrapper
https://github.com/nWidart/PHP-MySQLi-Database-Class
2) Always keep your database connection string to separate file and at safe place. then, include your connection file into your require project file.
3) Always validate value of your variables & use mysql_real_escape before using directly into query.
Try
$password = mysql_real_escape($_POST['password']); //to avoid SQL injunction
$username = mysql_real_escape($_POST['username']);
$credentials = "select * from Credentials where username = '$username' AND password = '$password' AND email_address = 'email_address'" ;

Categories