why does my 'if (isset) does not interact with mysql' - php

why does my 'if if (isset($_POST['submit'])) not interact with mysql'
Please tell me, where do I go wrong, I've been over this a thousand times and checked the internet... It's a lot of code, but I think I have overseen something. I made the remarks for myself, so I would'nt forget something stupid as an ";".
Thanks in advance
http://appsolute.vacau.com/cms
<html>
<head>
<title>Milan CMS</title>
</head>
<body>
<?php
mysql_connect("mysql15.000webhost.com", "a96443****tjiran", "ev****89") or die(mysql_error()); //opening database
mysql_select_db("a9644326_app") or die(mysql_error());
$result = mysql_query("select * from milan") or die(mysql_error()); //get msql database into $result
$content = mysql_fetch_array ($result); // make $content represent current entry
?>
<form action="<?php echo $PHP_SELF;?>" method="post" name="trainingen">
<h3>Trainingen:</h3><p><textarea name="nametrainingen" rows="10" cols="60"><?php echo $content['value']; ?></textarea></p>
<input type="submit" value="Verzenden"><input type="reset" value="Veld leeg maken">
</form>
<?php
if (isset($_POST['submit']))
{ //test if submit button is clicked
mysql_query("DELETE FROM milan WHERE tag='trainingen'") or die(mysql_error()); //delete old entry
$input = $_POST['nametrainingen']; //set $input as current entry
mysql_query("INSERT INTO milan (tag, value) VALUES ('trainingen', '$input')") or die(mysql_error()); //set tag, value as trainingen and $input(current entry)
$result = mysql_query("select * from milan") or die(mysql_error()); //reset $result to new database
$content = mysql_fetch_array ($result); //make $content represent new entry
$myFile = "trainingen.json";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, json_encode($content));
fclose($fh);
}
?>
<p>
</body>
</html>

$_POST is a super-global array that contains an associative array of all the form elements that were submitted with the form. You don't have an input with name="submit", so your isset() fails.

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" name="trainingen">
not $PHP_SELF

There is no tag whose "name" attribute is "submit" in your code.
Replace:
<input type="submit" value="Verzenden">
with:
<input name="submit" type="submit" value="Verzenden">

Try
<input type="submit" name="submit" value="Verzenden">
But warning -your code is insecure. Search for SQL injections in google.

In your submit button <input type="submit" value="Verzenden">. You have missed name="submit".
It should be
<input type="submit" value="Verzenden" name="submit">

The submit button doesn't pass anything through to the form. To confirm that, you can try var_dump($_POST). A substitute for that call would be
if (count($_POST))
However, you can still get notices and failed mysql queries so you should instead do
if (isset($_POST['nametrainingen']))

Related

how can i use only one file instead of 4 php files that are basically the same?

i basically have a simple porgram to count how many times a click a specific button and then send it to mysql, but for each button i have diferent tables and separated files. I would like to know if there is any way to join the 4 files into only one, since it is repeating the same thing 4 times in diferent files.
Here is my code:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Fct</title>
</head>
<body>
<form action="inserir.php" method="post">
<button name="A" type="submit" value="A">Senha A</button>
</form>
<form action="inserir2.php" method="post">
<button name="B" type="submit" value="B">Senha B</button>
</form>
<form action="inserir3.php" method="post">
<button name="C" type="submit" value="C">Senha C</button>
</form>
<form action="inserir4.php" method="post">
<button name="D" type="submit" value="D">Senha D</button>
</form>
</body>
</html>
and then the file to insert into mysql witch is inserir.php;
<?php
include 'bdados.php';
$A = $_POST['A'];
$query = "INSERT into `tipo1`(`senhaa`) VALUES ( '$A' )";
mysqli_query($dbconn, $query);
header("location: index.php");
?>
basically i have 4 "inserir.php" and i think i could shrink those 4 files in only one, i just dont know how.
All help is much apreciated :)
Add submit buttons with same name but different values.Retrieve the value by $_POST['name']
HTML
<form action="inserir.php" method="post">
<button name="val" type="submit" value="A">Senha A</button>
<button name="val" type="submit" value="B">Senha B</button>
<button name="val" type="submit" value="C">Senha C</button>
<button name="val" type="submit" value="D">Senha D</button>
</form>
PHP
<?php
include 'bdados.php';
$val = $_POST['val'];
$query = "INSERT into `tipo1`(`senhaa`) VALUES ( '$val' )";
mysqli_query($dbconn, $query);
header("location: index.php");
?>
I have a feeling your database schema could be improved, but without knowing the scope of your software, it's hard to make a recommendation. It looks like you want to change the table & the column-name based upon the value that is submitted. There are several different approaches that could help.
I'll change your query code to use a prepared statement (with PDO, as that's what I know)
PHP Switch
You'll have one file that handles all four of those submissions.
include 'bdados.php';
$key = array_keys($_POST)[0];
$value = $_POST[$key];
switch ($key){
case 'A':
$column = 'senhaa';
$table = 'tipo1';
break;
case 'B':
$column = 'senhab';
$table = 'tipo2';
break;
case ...
}
//The table name is hard-coded, so that part is not vulnerable to SQL injection
$query = "INSERT into `{$tableName}`(`senhaa`) VALUES ( :newValue )";
$bind = [':newValue'=>$value];
$pdo = new PDO(...);
$statement = $pdo->prepare($query);
$statement->execute($bind);//pass the ':newValue' to be bound
//Without binding, somebody could submit: `'');DELETE FROM senhaa WHERE (TRUE`
// This would close your INSERT statement with an empty value & delete everything from your table
// print_r($statement->errorInfo()); //for debugging if it doesn't work
header("location: index.php");
PHP Array
This will be much like above, but we'll replace the switch step with an array like:
$info = [
"A"=>['table'=>'tipo1','column'=>'tipo2']
"B"=> ['table'=>'tipo2'...]
...
];
$table = $info[$key]['table'];
$column = $info[$key]['column'];
Hidden HTML Inputs
Another approach could be to send identifying information through hidden input fields. While you should NOT send a table name this way, you could send some kind of identifier & then use the array-method above to map identifier to table info.
<form action="inserir-todo.php" method="post">
<button name="D" type="submit" value="D">Senha D</button>
<input type="hidden" name="identifier" value="the-fourth-table" />
</form>
Then you'd do:
$key = $_POST['identifier'];
$table = $info[$key]['table'];
...

echoing data from mysql_fetch_array

I'm trying to display data from my database table selected from a 'date'.
The query executes, but when I echo I don't get any result. Could you please help me with this?
<?php include 'includes/connection.php'; ?>
<html>
<head>
<title> </title>
</head>
<body>
<?php
if(isset($_POST['submitted'])){
$sql = "SELECT * FROM dagtaken WHERE datum = $_POST[datum]";
$result = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($result)){
echo $row['aantal'];
}
}else{
?>
<form action='' method='POST'>
<p><input type="date" name="datum"></p>
<p><input type='submit' value='Dagtaak toevoegen' />
<input type='hidden' value='1' name='submitted' /></p>
</form>
<?php } ?>
</body>
</html>
The query shouldn't execute, since dates are very obviously strings and require quotes. That said...
Try this:
mysql_query("SLEECT * FROM `dagtaken` WHERE `datum`='".mysql_real_escape_string($_POST['datum'])."'");
Now on to the actual problem, you are checking if(isset($_POST['submitted'])), but nowhere do I see <input name="submitted" in your source (EDIT Never mind, it has a stupid amount of whitespace pushing it off the edge). Try if(isset($_POST['datum'])), since that's the variable you actually use.
You haven't named your submit button, so your PHP code never kicks in. Don't check for form fields when all you really need is to check if a POST has occured.
Quick fix for you code:
<input type="submit" name="submitted" value="Dagtaak toevoegen" />
^^^^^^^^^^^^^^^^^
Better fix:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
your code here ...
}
First, Escape your data. SQL injection is now very easy
Second, do you have data in your database?
Try print_r($row) instead of echo $row...
$_POST is with quotes...=> $_POST["datum"]
Last addition, is your date the same as your input?

UPDATE inside a WHILE statement

So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...

Zero values getting inserted in the database table

This is the piece of code which I'm using to open up a pop up window with the variable $query_string which is being used to save the entries made in the form.
echo'<script language = "JavaScript" type="text/javascript">
//<![CDATA[
window.open(\'./save.php?'.$query_string.'\',\'save\',\'location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes\');
Then i have used to save.php to display a submit button and written an insert statement to put the data into the database.The problem is the rows are getting populated with 0 in the database table.Any mistakes committed?
if($_POST['formSubmit'] == "Submit")
{
//appending the date to store in the database.
$entry_date_array = array($_REQUEST["year"],$_REQUEST["month"],$_REQUEST["day"]);
$entry_date = implode('-', $entry_date_array);
echo "$entry_date";
//appending aggr nr and fetching the id from the database.
$aggr_nr = $_REQUEST['list_nr_01'].$_REQUEST['list_nr_02'].$_REQUEST['list_nr_03'];
$sql="SELECT v.id FROM aggregatenumber AS v WHERE v.aggr_nr = '".$aggr_nr."'";//missing Quotes
$aggr_id = #mysql_query($sql);
$result = #mysql_fetch_array($aggr_id);
$test= $result['id'];
echo "$test";
$sql_einl_sp = "INSERT INTO search_parts(entry_date,aggr_nr)values('".$entry_date."','".$test."')";
$result_einl_sp = #mysql_query($sql_einl_sp);
Html
<body>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<h>Save Information</h>
<input type="submit" name="formSubmit" value="Submit" />
<input type="submit" name="btncancel" value="Cancel"/>
</form>
</body>
Change
$sql_einl_sp = "INSERT INTO search_parts(entry_date,aggr_nr)
values('".$entry_date."','".$test."')";
To
$sql_einl_sp = "INSERT INTO search_parts(entry_date,aggr_nr)
values('".$entry_date."',".$test.")";
Try printing the query to see what exactly goes to the database.
It may possible that the variables in query are empty or 0, or
you may not have correctly defined the datatypes in table for this particular fields.

Checking Which Button was Clicked

I have a PHP generated form which consists of a list of items, each with a button next to them saying "Remove This" it outputs similar to below:
Item A - [Remove This]
Item B - [Remove This]
...
I wish to be able to click Remove This and it will detect which item it is, and then remove that from the database. Here's my code so far:
selectPlaces.php
<?php
include 'data.php';
mysql_connect($host, $user, $pass) or die ("Wrong Information");
mysql_select_db($db) or die("Wrong Database");
$result = mysql_query("SELECT * FROM reseller_addresses") or die ("Broken Query");
while($row = mysql_fetch_array($result)){
$placeName = stripslashes($row['b_name']);
$placeCode = stripslashes($row['b_code']);
$placeTown = stripslashes($row['b_town']);
$outputPlaces .= "<strong>$letter:</strong> $placeName, $placeTown, $placeCode <input type=\"button\" onclick=\"removePlace()\" value=\"Remove This\" /><br />";
}
mysql_close();
?>
Coupled with my admin.php
<div id="content" style="display:none">
Remove a Place<br><br>
<?php include 'selectPlaces.php'; echo $outputPlaces; ?>
</div>
I know I need to add some javascript to detect which button is clicked but I can't seem to get it working. I tried modifying the onclick="removePlace()" by perhaps passing a variable in the function removePlace(placeID) or something like that, but I'm new to JavaScript and I have no idea how to receive this in the removePlace function.
This seems easier to do without JavaScript. For each entry instead of generating just a button, generate a form that posts to a PHP script that does the deleting.
<form action="deletePlace.php?id=<?php echo $idOfThePlace?>">
<input type="submit" value="Remove This" />
</form>
$idOfThePlace would be the ID with you use to identify the data row.
You don't need JavaScript for that. Try running this example:
<?php var_dump($_POST); ?>
<form action="post.php" method="post">
<p>
<input type="submit" value="a" name="action" />
<input type="submit" value="b" name="action" />
</p>
</form>
You'll see that $_POST['action'] will depend on which button was pressed. For your example, you just need to set the value to identify the item that needs to be deleted. It might be useful to use the <button> element for that: <button name="delete" type="submit" value="12345">delete item 12345</button>. It'll show up as $_POST['delete'] with 12345 as value when submitted.

Categories