Zero values getting inserted in the database table - php

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.

Related

PHP / MySQL: Insert multiple data from checkbox and save it to multiple row in a table

I'm new to PHP Programming and MySQL. Regarding my question, I have 3 checkboxes. I need to select the data and save it to the database. if I choose 2 data, thus need to save the data 1 by 1, which means will insert two row of data. Below is my code example:
index.php
<!DOCTYPE html>
<html>
<body>
<h1>Show Checkboxes</h1>
<form action="save.php" method="POST">
<input type="checkbox" name="club[]" value="Chelsea">
<label for="Chelsea"> Chelsea</label><br>
<input type="checkbox" name="club[]" value="Liverpool">
<label for="Liverpool"> Liverpool</label><br>
<input type="checkbox" name="club[]" value="Arsenal">
<label for="Arsenal"> Arsenal</label><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
save.php
<?php
include("connect.php");
$club = implode(',',$_POST['club']);
$query = "INSERT INTO bpl_club (club_name) VALUES ('$club')";
$sql = $conn->prepare($query);
$sql->execute();
if($sql){
echo "<script>alert('Record inserted successfully!')</script>";
echo "<script>window.location = 'index.php'</script>";
}else{
echo "<script>alert('Something went wrong. Please try again!')</script>";
}
?>
Can anyone know how to fix it? Thank you so much..
Use foreach function to print your check box one one by from $_POST['club'] array
$ClubArray=array();
$ClubArray=$_POST['club'];
foreach($ClubArray as $ClubName)
{
//your Insert code here with the insert query ie INSERT INTO bpl_club (club_name) VALUES ('$ClubName')
}

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'];
...

Database Query failed error when inserting Row into Table

I am getting Database query failed error while trying to insert a new row into a table. This table (pages) has a column (subject_id) referencing another table (subjects). I am passing the value of the of the subject_id from the url and it is passed on the form correctly. All the values seem to be passed correctly on the form using php, but i get error while i try to insert the row. The form submits to itself.
select_all_pages_by_subject($sid) is a function that selects all rows (pages) from the current subject (passed from the url). It works fine for the position field.
I suspect this error is probably a MySQL syntax error somewhere in my code, but i just cant seem to figure it out yet. I appreciate some help. Thank you.
Here is my code:
<div class="body_content">
<?php
$sid = null;
if(isset($_GET["subject"])) {
$sid = $_GET["subject"];
}
?>
<form action="create_page.php" method="post">
Menu Name: <input type="text" name="menu" /> <br>
Position: <select name="position">
<?php
$new_page_query = select_all_pages_by_subject($sid);
$page_count = mysqli_num_rows($new_page_query);
for($count=1; $count<=($page_count + 1); $count++) {
echo "<option value=\"$count\">$count</option>";
}
?>
</select> <br>
Visible:<br>
No <input type="radio" name="visible" value="0" />
Yes <input type="radio" name="visible" value="1" /> <br>
Subject ID: <input type="text" name="subject_id" value="<?php echo $sid; ?>" /> <br>
Content: <br>
<textarea rows="5" cols="40" name="content"></textarea> <br>
<input type="submit" value="Create Page" name="submit" /> <br>
Cancel <br>
</form>
<?php
if(isset($_POST['submit'])) {
$menu_name = $_POST["menu"];
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$content = $_POST["content"];
$subject_id = (int) $_POST["$sid"];
$insert_query = "INSERT INTO pages (subject_id, menu_name, position,
visible, content) VALUES ({$subject_id},'{$menu_name}', {$position},
{$visible}, '{content}')";
$page_insert = mysqli_query($connection, $insert_query);
if($page_insert) {
$_SESSION["message"] = "Page created successfully";
redirect_to("admin.php");
} else {
$_SESSION["message"] = "Page creation failed";
redirect_to("create_page.php?subject=$sid");
}
}
?>
</div>
Edit: removed the WHERE statement
The problem is INSERT cannot have a WHERE after it.
$insert_query = "INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES ({$subject_id},'{$menu_name}', {$position}, {$visible}, '{content}')";
So after some troubleshooting, i decided to separate the form and form processing into 2 different pages, then i realized the problem, in the form action, i did not specify the subject id in the URL since i was passing the id from the URL:
<form action="create_page.php" method="post">
should be:
<form action="create_page.php?subject=<?php echo $sid; ?>" method="post">
Edit: I have also noticed that the "Database query failed" error was being called on the Position form field where i was making a database connection on the "pages" table to pull the number of rows. So when the insert statement failed due to the absence of subject id from the url, php did not process the page past the position form field, it called the error on the field and stopped execution. When insert query fails, parts of the form are displayed on the screen (only the menu name field and the position field with empty values). When i tried to view source code for errors, it requested the page be reloaded again (felt like an infinite loop running or something)

If input exists from one table update it on another one

Im trying to make like a refill code that will refill my table.
I have one table that have my refill code in it and other table that stores the balance of the account.
table1: card_credit (table that stores the balance of the account)
table2:card_refill (table that have me refill code)
I have created this code with session and PHP. Now I'm stuck and dont know how to move forward.
I want to make when i write in the refill code from table card_refill that its take the amount of credit into value in table card_refill
refill.php
<strong>Refill</strong>
<form action="refill.php" method"post">
<input type="text" name="refillcode"/>
<br>
<input type="submit" name="Submit" value="Refill" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['refillcode'] = $_POST['refillcode'];
}
?>
Here is a possible solution, I am just don't know, where the card_id comes from.
This is inserting a new record into your card_credit table.
// starting the session before any output
session_start();
//include here the database connection file!
//for example:
//include('db_connection.php');
if (isset($_POST['Submit'])) {
//First do a validation here, is the refillcode number, exists, etc...
//Insert it into the table
$sql = "INSERT INTO card_credit (card_id, value) VALUES ('[YOUR_CARD_ID_HERE]', " . intval($_POST['refillcode']) . ")";
//Link is the resource variable when you created the mysqli_connect
mysqli_query($link, $sql);
//Redirect here if you want
}
?>
<!-- HTML CODE STARTS HERE -->
<strong>Refill</strong>
<form action="refill.php" method="post">
<input type="text" name="refillcode"/>
<br>
<input type="submit" name="Submit" value="Refill" />
</form>

Using a Submit Button to insert an entry into a MySQL database via PHP?

I'm pretty new to PHP, so I'm not quite sure on what to do with this.
Basically I'm trying to insert an entry into my MySQL database, through a "submit" button in HTML. I can't seem to get this to work, is it possible?
<?php
include('db_connect.php');
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
?>
The INSERT works perfectly fine on its own, but I want it to be executed when the "submit" button is pressed.
Any help would be greatly appreciated.
Thanks
Tobo.
Just set the action of the form to the URL of the script that performs the insert.
Note that since you are modifying a database, the request is probably non-idempotent and you should use the POST method.
<form action="/path/to/your/script.php" method="post">
<input type="submit">
</form>
<form method="post">
<input type="submit" name="submit" value="submt"/>
</form>
PHP
<?php
if(isset($_POST['submit']))
{
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
}
?>
You can check button value is posted and can execute line of code in it.
<?php
include('db_connect.php');
if(isset($_REQUEST['SUBMIT_BUTTON_NAME']))
{
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
}
?>
Hope this will be helpful to you
I had for the submit details:
<form id = "submitForm" action="config/profile_save.php" method="post">
<button type="submit" class="button" name="submit" value="submit">Save Profile</button></form>
Inside each input field on the page, I placed form = "submitForm"
I then changed the name too.(This is the super global variable later)
<input type="text" autofocus="true" class="custom_link_url_text" id="custom_link_url_text"
name="custom_link_email" placeholder="Enter your public email address" spellcheck="false"
style="width: 245px;" maxlength="75" form = "submitForm">
I was then able to capture the data on the next page using the name as POST variable.
if(isset($_POST['submit'])) {
$custom_link_email = $_POST['custom_link_email'];
}
Once I did that it was just a case of inserting data into the database.

Categories