PHP query inserts 2 rows into the table - php

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?

Related

Condition to Skip Input field if Empty

I'm trying to set a condition wherein if the 'filefield' is empty, it will skip the insert in DB as it is only an option and just proceed in inserting of 'name' and 'description' in the DB, which will never be empty.
<?php
include("connection.php");
if (isset($_POST['submit']))
{
$name = mysqli_real_escape_string($conn, $_POST['name']);
$description = mysqli_real_escape_string($conn, $_POST['description']);
if ($name == '' || $description == '' )
{
$error = 'ERROR: Please fill required fields!';
renderForm($name, $description);
}
else
{
if(!empty($_FILES['filefield'])){
if(isset($_FILES['filefield'])){
$file=$_FILES['filefield'];
$upload_directory='uploads/';
$ext_str = "gif,jpg,jpeg,mp3,tiff,bmp,doc,docx,ppt,pptx,txt,pdf";
$allowed_extensions=explode(',',$ext_str);
$ext = substr($file['name'], strrpos($file['name'], '.') + 1);
if (!in_array($ext, $allowed_extensions) )
{
echo '<script language="javascript">';
echo 'alert("file type not allowed for upload")';
echo '</script>';
exit();
}
$path=md5(microtime()).'.'.$ext;
if(move_uploaded_file($file['tmp_name'],$upload_directory.$path)){
$filefield = $_FILES["filefield"]["name"];
$path = $path."/".$filefield;
}
}
}
}
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);
if($result)
{
echo '<script language="javascript">';
echo 'alert("Success!")';
echo '</script>';
exit();
}
}
?>
I'm not sure how to proceed with the condition. Any help is highly appreciated.
First, close off all of your logic, including if(move_uploaded_file), so that the $query is competely outside of any conditionals. Then it's just a matters of checking whether the filefield was filled out or not. If it's not empty, your $query insert all three fields. If it is, your $query only inserts $name and $description.
This can be seen in the following (heavily cut-down) code:
/* Existing logic */
else
{
if (!empty($_FILES['filefield'])) {
if (isset($_FILES['filefield'])) {
if (move_uploaded_file($file['tmp_name'], $upload_directory.$path)) {
...
$path = $path."/".$filefield;
}
}
}
}
/* Modified logic */
if (!empty($_FILES['filefield']) || !isset($_FILES['filefield'])) {
$query = "INSERT INTO `item`(`name`, `description`, `path`) VALUES ('$name','$description','$path')";
}
else {
$query = "INSERT INTO `item`(`name`, `description`) VALUES ('$name','$description')";
}
$result = mysqli_query($conn, $query);

PHP form submiting

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

query wongt output to table. correct syntax

What am i doing wrong here?
(Know its mysql)
this else is not working it look like. user can insert same modul id many times.
$besvarelse = $_GET['besvarelse'];
$modulid = $_GET['modulid'];
$username = $_GET['username'];
$tilkobling = kobleTil();
if (!empty($besvarelse) ) {
$insert = mysql_query("INSERT INTO oppgave (besvarelse, modulid, username) VALUES ('$besvarelse', '$modulid','$username')");
if($insert) {
echo "<h1>Levering OK</h1><br>";
}
}
else {
die("<h1>Du har lever før</h1>");
}
?>
Try with this and post the errors that PHP shows, please:
//Assuming that connection to mysql server its done somewhere with mysql_connect()
error_reporting(E_ALL); ini_set('display_errors', 1);
explode($_GET);
echo "<pre>";
print_r($_GET); //Just to see what's on the variables...
echo "</pre>;
// $tilkobling = kobleTil(); Need to explain this line
if (!empty($besvarelse) ) {
$sql = "INSERT INTO oppgave (besvarelse, modulid, username) VALUES ('$besvarelse', '$modulid','$username')";
if($insert = mysql_query($sql))
{
echo "<h1>Levering OK</h1><br>";
}
else {
die("<h1>Du har lever før</h1>");
}
} // you were missmatching the IF closing bracket
?>
try to check for exist rows like
$besvarelse = $_GET['besvarelse'];
$modulid = $_GET['modulid'];
$username = $_GET['username'];
$tilkobling = kobleTil();
if (!empty($besvarelse) ) {
// check exist moduleid
$check = mysql_query("select * from oppgave where modulid = '$modulid'");
$conut_rows= mysql_num_rows($check);
if($conut_rows > 0) {
echo "module id already exist";
}
else {
$insert = mysql_query("INSERT INTO oppgave (besvarelse, modulid, username) VALUES ('$besvarelse', '$modulid','$username')");
if($insert) {
echo "<h1>Levering OK</h1><br>";
}
else {
die("<h1>Du har lever før</h1>");
}
}
}

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.

success/error message for insert into mysql database

when the info is successfully inserted, it's displaying the error message and saying that it's a duplicate entry for a primary key...I can't figure out why!
<?
$email=$_POST['email'];
$pw=$_POST['pw'];
mysql_connect('***','***','***');
#mysql_select_db('***') or die('Unable to select database');
$query = "INSERT INTO test_table VALUES ('','$email','$pw')";
mysql_query($query) or die(mysql_error());
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
mysql_close();
?>
You are executing the query twice: first, in mysql_query($query) or die(mysql_error()); and second, in if(mysql_query($query)). So the second time the query executes the record is already there and thus the insertion fails.
You are executing same query twice.
$query_result = mysql_query($query) or die(mysql_error());
if ($query_result) {
echo 'success';
} else {
echo 'failure' . mysql_error();
}
Write this way, hope it will work.
Just delete this code from your php script and it will be fine.
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
You make it running error twice in a time. You can also use mysql_affected_rows() to make sure the data is executed in database server. Return a string type value.
<?
$email=$_POST['email'];
$pw=$_POST['pw'];
mysql_connect('***','***','***');
#mysql_select_db('***') or die('Unable to select database');
$query = "INSERT INTO test_table VALUES ('','$email','$pw')";
if(mysql_query($query))
{
echo 'Data executed : '.mysql_affected_rows();
}
else
{
echo 'failure' .mysql_error();
}
mysql_close();
?>
Good luck and let me know the result.
$email=$_POST['email'];
$pw=$_POST['pw'];
$alerts = array();
if (trim($_POST['email']) == '') {
$alerts[] = "<div class='alert alert-danger' role='alert'> Enter your Email! </div>"; }
if (trim($_POST['pw']) == '') {
$alerts[] = "<div class='alert alert-danger' role='alert'> Enter your PW! </div>"; }
if (!count($alerts)) {
$query = "INSERT INTO test_table (email, pw) VALUES ('".$email."', '".$pw."')";
mysqli_query($this->conn, $query) or die (mysqli_connect_error());
return ['success' => true];
} else {
return ['success' => false, 'alert_m' => implode($alerts)."<br>"];
}

Categories