PHP form submiting - php

I have a form with four values, player1, player2, awayTeam, and homeTeam.
After checking if values are not empty it does not want to send results to database. I am not sure why it does not want to submit.
There are as well two random numbers which will be compared and based on if num1 > num2 record should be submitted.
<?php
$link = mysqli_connect("localhost","test", "passowrd", "test" );
if (mysqli_connect_error()) {
die ("DB has not been connected");
}
// create two random numbers
$Num1 = rand();
$Num2 = rand();
if (isset($_POST['submit'])) {
$playerOne = mysqli_real_escape_string ($link, $_POST['playerOne']);
$playerTwo = mysqli_real_escape_string ($link, $_POST['playerTwo']);
$awayTeam = mysqli_real_escape_string ($link, $_POST['awayTeam']);
$homeTeam = mysqli_real_escape_string ($link, $_POST['homeTeam']);
//check if player one is empty
if (empty($playerOne)) {
echo "Game Creator PSN required!" . "<br>";
}
//check if player two is empty
if (empty($playerTwo)) {
echo "Second Player PSN required!";
}
} else {
//compare two numbers
if ($Num1 > $Num2) {
$sql = "INSERT INTO randomizer (playerOne, playerTwo, awayteam, homeTeam) VALUES (' $playerOne', '$playerTwo', '$awayTeam', '$homeTeam')";
if ($link->query($sql) === true) {
echo "Record Added Sucessfully";
} else {
echo "There was a problem";
}
} else {
$sql = "INSERT INTO randomizer (playerOne, playerTwo, awayteam, homeTeam) VALUES (' $playerTwo', '$playerOne', '$awayTeam', '$homeTeam')";
if ($link->query($sql) === true) {
echo "Record Added Sucessfully";
} else {
echo "There was a problem";
}
}
}
?>

if post data is null, you did nothing. I've never see exit or other exit words, in the SQL words you'll get errs
what different with $num1 > $num2 in your code? they executed the same codes

Related

I want to implement something that doesn't allow the user to rate more than once

I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.

Echo error message if one input value is greater than other in php

I have a form that saves 5 input values to an inventory in data base. The problem is, i need it to return an error message if "Value" is larger than "Buy_Value". Right now it prints the error message, but still submits the data to data base which is no use for me. Am I just using the function in the wrong place in the code?
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['ID'])&&isset($_POST['Name'])&&isset($_POST['Inventory_number'])
&&isset($_POST['Value'])&&isset($_POST['Buy_Value'])){
$ID=$_POST['ID'];
$Name=$_POST['Name'];
$Inventory_number=$_POST['Inventory_number'];
$Value=$_POST['Value'];
$Buy_Value=$_POST['Buy_Value'];
//echo "<p>".$ID." ".$Name." ".$Inventory_number."</p>";
include('config.php');
if ($Value > $Buy_Value) {
echo("The 'buy value' must be greater than 'value'");
}
$sql="INSERT INTO $mysql_database.`inventory`
(`id`, `Name`, `Inv_Nr`, `value`, `buy_value`)
VALUES ('$ID', '$Name', '$Inventory_number', '$Value', '$Buy_Value')";
$result=mysql_query($sql);
tab($sql);
mysql_close($bd);
}
}
function tab($sql){
if (!mysql_errno())
{
echo "<br />Data submitted";
}
else
{
echo "<br />Error: " . mysql_error();
}
}
?>
Use exit instead of echo for the following line
exit("The 'buy value' must be greater than 'value'");
put your database query execution in else part then it will not executed if below
if ($Value > $Buy_Value) {
condition is meet.
try this:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['ID']) && isset($_POST['Name']) && isset($_POST['Inventory_number'])
&& isset($_POST['Value']) && isset($_POST['Buy_Value'])
) {
$ID = $_POST['ID'];
$Name = $_POST['Name'];
$Inventory_number = $_POST['Inventory_number'];
$Value = $_POST['Value'];
$Buy_Value = $_POST['Buy_Value'];
//echo "<p>".$ID." ".$Name." ".$Inventory_number."</p>";
include('config.php');
if ($Value > $Buy_Value) {
echo("The 'buy value' must be greater than 'value'");
} else {
$sql = "INSERT INTO $mysql_database.`inventory`
(`id`, `Name`, `Inv_Nr`, `value`, `buy_value`)
VALUES ('$ID', '$Name', '$Inventory_number', '$Value', '$Buy_Value')";
$result = mysql_query($sql);
tab($sql);
mysql_close($bd);
}
}
}
function tab($sql)
{
if (!mysql_errno()) {
echo "<br />Data submitted";
} else {
echo "<br />Error: " . mysql_error();
}
}

empty field to mysql using php

i have code for save 3 textbox in one field in databse
no problem when i am enter 3 textbox , but when i fill 1 textbox and press ok
save another textbox in database as blank
i want just take the textbox is fulled and ignore the textbox empty
this is my code
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result=mysql_query($sql);
$result2=mysql_query($sql2);
$result3=mysql_query($sql3);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
Execute your sql query only the variable value not equal to empty.
try this,
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if ($expert_name != "") {
$sql = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result = mysql_query($sql);
}
if ($expert_name2 != "") {
$sql2 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2 = mysql_query($sql2);
}
if ($expert_name != "") {
$sql3 = "INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 = mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if ($result || $result2 || $result3) {
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
//mysql_close($con);
?>
back to form add
You should also check $result2 and $result3. I added that in this answer
try this
if ( !empty($_POST['expert_name']) ){
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if ( !empty($_POST['expert_name2']) ){
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if ( !empty($_POST['expert_name3']) ){
$sql3 ="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3 =mysql_query($sql3 );
}
Then you might want to check if the variable is empty().
<?php
include("connect.php");
$expert_name = trim($_POST['expert_name']);
$expert_name2 = trim($_POST['expert_name2']);
$expert_name3 = trim($_POST['expert_name3']);
// this is for arabic language.
mysql_query("SET NAMES utf8");
// Insert data into mysql
if(!empty($expert_name)) {
$sql="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name')";
$result=mysql_query($sql);
}
if(!empty($expert_name2)) {
$sql2="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name2')";
$result2=mysql_query($sql2);
}
if(!empty($expert_name3)) {
$sql3="INSERT INTO experts(id,expert_name) VALUES(NULL, '$expert_name3')";
$result3=mysql_query($sql3);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
else {
echo "ERROR";
echo "<br>";
// this for print error in insert process
echo mysql_error();
echo "<a href='expert_add.php'><br>Please try again </a>";
}
Also note: You only check if $result is okay. If you only fill textbox 2 and leave 1 empty, the value of 2 it will get inserted but an error is shown.
I'd say your code need general review, but as it is for now you will have to do something like this each query:
if (!empty($expert_name2){
$result2=mysql_query($sql2)
}
But you should try to loop your queries in foreach rather than manually write every on query. And by the way:
if($result){
echo "Successful";
echo "<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
}
This code only return succes when 1st wuery success because you use $result which is set in 1st query only
The ID is probably NOT NULL AUTO_INCREMENT, so that won't accept NULL as value.
try sending blank value, such as:
$sql="INSERT INTO experts(id,expert_name) VALUES ('', '$expert_name')";
Also, build bulk insert, rather than multiple.
I will explain why, when you insert single insert into the database, the values being inserted, then, the DB engine flushes indexes (they written to disk), unless you have set delay_key_write=ALL in you my.cnf. Index flushing directly affects your db performance.
Please, check the reworked code out. The code adjusted for bulk insert, sql string escaping for security purposes and additional verification for post keys existence.
<?php
include("connect.php");
// this is for arabic language.
mysql_query("SET NAMES utf8");
$values = array();
$skipInsert = true;
$fields = array('expert_name', 'expert_name2', 'expert_name3');
$insert = "INSERT INTO experts(id,expert_name) VALUES ";
// Loop through predefined fields, and prepare values.
foreach($fields AS $field) {
if(isset($_POST[$field]) && !empty($_POST[$field])) {
$values[] = "('', '".mysql_real_escape_string(trim($_POST[$field]))."')";
}
}
if(0 < sizeof($values)) {
$skipInsert = false;
$values = implode(',', $values);
$insert .= $values;
}
if(false === $skipInsert) {
mysql_query($insert);
}
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful","<BR>";
// echo "<a href='formadd.php'>Back to main page</a>";
} else {
echo "ERROR","<br>",mysql_error(),"<a href='expert_add.php'><br>Please try again </a>";
}
HTH,
VR
if(!empty($textbox1_value)) {
//DO SQL
}
You can repeat this for multiple boxes however you wish, the empty operator checks if its empty, so if its not empty the "//DO SQL" area will get run.

PHP code not entering the data into database

$name = $_GET['fullname'];
$phone = $_GET['phone'];
$address = $_GET['address'];
$size = $_GET['size'];
$toppings = $_GET['toppings'];
$delivery = $_GET['type'];
mysql_connect ("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db ("pizzaorders");
$query ="INSERT INTO orders (fullname, phone, address, size, toppings, delivery) VALUES ('".$name."', '".$phone."', '".$address."','".$size."','".$toppings."','".$delivery.")";
$done=mysql_query($query);
echo $done;
$total = 0;
$total = sizecost() + deliverycost() + toppingcost();
echo " $name your {$_GET["size"]} pizza will come in 45 minutes.";
echo "Total: $ $total";
echo " Your Toppings are ";
foreach($toppings as $topping) {
echo $topping ;
}
echo "Your Delivery Type:{$_GET["type"]}";
echo "Database Updated";
function sizecost() {
$size = 0;
if ($_GET['size'] == "Small"){
$size+=5;
}
else if ($_GET['size'] == "Medium"){
$size+=10;
}
else if ($_GET['size'] == "Large"){
$size+=15;
}
return $size;
}
function toppingcost() {
$toppings = $_GET['toppings'];
foreach($toppings as $topping) {
$topping=1;
$topping=$topping+1;
}
return $topping;
}
function deliverycost() {
$deliverycost = 0;
if ($_GET['type'] == "delivery") {
$deliverycost += 5;
}
return $deliverycost;
}
Last value is missing a single quote at the end.
Use echo mysql_error after mysql_query
IMPORTANT
You MUST use mysql_real_escape_string() to protect against [my]sql injection.
You can save a lot of effort with using PDO;
$db = new PDO('mysql:host=localhost;dbname=pizzaorders', "root", "");
$query = $db->prepare("INSERT INTO orders
(fullname, phone, address, size, toppings, delivery)
VALUES (?,?,?,?,?,?)");
$query->execute(array($name, $phone, $address, $size, $toppings, $delivery));
Or you can just use the $_GET[] variables there.
first you could print the erros on the screen so you know what's wrong
$done=mysql_query($query) or die(mysql_error());
and second, you are missing a quote at the end
,'".$delivery.")"; should be ,'".$delivery."')";
Edit:
to answer your second question:
I don't think you can use $_GET['type'] inside a function
better to get the type outside a function and then pass it as a parameter, like follow:
$type = mysql_real_escape_string($_GET['type']);
deliverycost($type);
and in your function
function deliverycost($type)
{
if(empty($type))
{
//throw error, type cannot be empty
}
$deliverycost = 0;
if ($type == "delivery") {
$deliverycost += 5;
}
return $deliverycost;
}
Make sure you escape the single quotes like:
mysql_real_escape_string($name)
The query would be:
$query ="INSERT INTO orders (fullname, phone, address, size, toppings, delivery)
VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($phone)."', '".mysql_real_escape_string($address)."','".mysql_real_escape_string($size)."','".mysql_real_escape_string($toppings)."','".mysql_real_escape_string($delivery)."')";
Also echo the query to see what query is being sent to the database.

PHP query inserts 2 rows into the table

OK, here is the deal. I have 3 queries putting data in different tables. 2 of them are in included files. I've tried to put them into the main code, the result was the same. The first two queries inserts one row with the data and a blank row. The third works fine. Here is the code.
This in the main page:
<? $p=0;
if ($select2)
{
$event=$select2;
}
else
{
require_once("insert_gal_name.php5");
}
if ($select)
{
$folder=$select;
}
else
{
require_once("insert_folder.php5");
if (file_exists("Connections/".$folder))
{
}
else
{
mkdir("Connections/$folder",0777);
}
}
while($p<$number)
{
$p++;
$dir = 'Connections/'.$folder.'/'; // Директорията в която ще се записват файловете
copy($_FILES['file']['tmp_name'][$p],"$dir".$_FILES['file']['name'][$p]); //Копиране на файла
echo "Файлът бе качен успешно!<br>"; // Извеждане на съобщение показващо, че файла е качен
if($_FILES['file']['name'][$p])
{
$real_file_name = $dif_of_files.$_FILES['file']['name'][$p];
$nom_file = str_replace(" ", "", $real_file_name); }
$query = "INSERT INTO gallery (name, title, day, month, year) VALUES ('$nom_file', '$event', '$day', '$month', '$year')";
$result = mysql_query($query) or die(mysql_error());
}
if (!$result)
{
echo "Error";
}
else
{
echo "All data was uploaded successfuly.";
}
?>
And here are the includes in the order they are placed in the source
<? $query = "INSERT INTO gallery_names (name) VALUES ('$event')";
$result = mysql_query($query) or die(mysql_error());
if (!$result)
{
echo "Error";
}
else
{
echo "The gallery was created successfuly.";
}
?>
<? $query = "INSERT INTO folders (name) VALUES ('$folder')";
$result = mysql_query($query) or die(mysql_error());
if (!$result)
{
echo "Error";
}
else
{
echo "The folder was created successfuly.";
}
?>
<?
if($event!='')
{
$query1 = "INSERT INTO gallery_names (name) VALUES ('$event')";
$result1 = mysql_query($query1) or die(mysql_error());
if (!$result1)
{
echo "Error";
}
else
{
echo "The gallery was created successfuly.";
}
}
?>
If $select2 is false then this code will do two inserts. If $event is empty one of these will be an empty row which sounds like the problem you're having.
What are the values of $select2 and $event? Have you tried debugging them?

Categories