I am pretty much new to php and mysql .I am trying to create a php form
which data will be stored in backend Mysql database
I have created two php files
Form.php
insert.php
And both these files have an require_once(DB_Login.php) function which
connects to the Mysql DB
The contents of Form.php---
<html>
<head>
<body>
<form action="insert.php"
method="POST">
<?php
require_once('DB_Login.php');
$sql=mysql_query("Select * from Department");
echo '<table border=1px>';
echo '<th>DepartmentId</th> <th>Department_Name</th><th>
Description</th>';
$datas=array();
while($data=mysql_fetch_array($sql))
{
$datas[]=$data;
//Running a loop all contents in the Mysql Table
echo '<tr>';
echo '<td>.$datas[\'Dept_Id\'] </td> <td>.$datas[\'Dname\']</td>
<td>.$datas[\'Description\']</td>';
echo '</tr>';
}
echo'<tr>';
echo'<td><input type=\"text\" name=\"Dept_Id\" id=\"Dept_Id\"></td><td>
<input type=\"text\" name=\"Dname\" id=\"Dname\"></td> <td><input
type=\"text\" name=\"Description\" id=\"Description\"></td>';
echo'</tr>';
echo '</table>';
echo'<input type="submit" value="SEND">';
?>
</form>
</body>
</head>
</html>
The contents of insert.php--
<?php
require_once('DB_Login.php');
$Didtext = mysql_real_escape_string($_POST['Dept_Id']);
$Dnametext=mysql_real_escape_string($_POST['Dname']);
$Desctext=mysql_real_escape_string($_POST['Description']);
echo $Didtext;
echo $Dnametext;
$adddept="INSERT INTO Department('Dept_Id','Dname','Description')
values('$Didtext','$Dnametext','$Desctext')";
$result = mysql_query($adddept);
if($result)
{
echo("<br>Input data is succeed");
}
else
{
echo("<br>Input data failed");
}
?>
The problem think is values are not being passed to insert.php
$Didtext = mysql_real_escape_string($_POST['Dept_Id']);
$Dnametext=mysql_real_escape_string($_POST['Dname']);
$Desctext=mysql_real_escape_string($_POST['Description']);
After i run this code I get the message Input data failed.
I did a lot of search for this question .
I am using id attribute to pass element value to insert.php
Please help !!!
You should not use apostrophe (') when labeling your column names. Remove them.
Your insert query should look like this:
$adddept="INSERT INTO Department(Dept_Id, Dname, Description)
VALUES('$Didtext','$Dnametext','$Desctext')";
Also, make sure that your $_POST values from your form is the same with the name HTML tags of your input fields. You don't need to use backslash (\) when assigning a name tag on your input fields in your case, where you are using ' to echo and you are using " on assigning HTML tags.
<input type="text" name="Dept_Id" id="Dept_Id">
And double check the table name and column names that you use in your queries, because these data are case sensitive.
Note: You shouldn't be using the deprecated mysql_* API anymore and instead use mysqli_* prepared statement.
UPDATE:
Change your Form.php code as:
...
...
echo '<tr>';
echo '<td><input type="text" name="Dept_Id" id="Dept_Id"></td>';
echo '<td><input type="text" name="Dname" id="Dname"></td>';
echo '<td><input type="text" name="Description" id="Description"></td>';
echo '</tr>';
echo '</table>';
No need to write " \" before double quotes.
You did not pass the variables in which you store the value. Do the below change in insert.php:
$adddept="INSERT INTO Department('Dept_Id','Dname','Description')
values('".$Didtext."','".$Dnametext."','".$Desctext."')";
NOTE: If Dept_Id is int then no need to use ' before and after the variable $Didtext as :
$adddept="INSERT INTO Department('Dept_Id','Dname','Description')
values(".$Didtext.",'".$Dnametext."','".$Desctext."')";
Related
I am working on a project where I want to display a dropdown list from database which I am able to do but I am stuck on the part after selection is made and I am not getting the selected value in database.
<form action="" method="post">
<div class="close">+</div>
<h2> Select preferred advisor from dropdown</h2>
<?php
$query="SELECT advisor_name FROM advisor_names";
$queryenter code here_run=mysqli_query($con,$query);
if(mysqli_num_rows($query_run)>0)
{
echo '<select name="Advisors">';
while($row=mysqli_fetch_assoc($query_run))
{
$selected_advisor=$rows['advisor_name'];
echo "<option value>".$row["advisor_name"]."</option>";
}
echo '</select>';
}
?>
<br><br>
<input name="mod_btn" type="submit" class="button" value="Submit">
<!-- <input name="mod_btn" type="submit" class="button"> -->
<!--<input type="submit">-->
<?php
if(isset($_POST['mod_btn']))
{
$query="INSERT INTO `appointment`(`number`, `advisor`) VALUES (NULL,'$selected_advisor');";
$query_run=mysqli_query($con,$query);
if($query_run)
{
echo '<script type="text/javascript"> alert("Query run sucessful")</script>';
}
}
The query executes but the value is not shown in the database.
You don't populate a value for each option and by specifying value in the option tag you're making the value blank:
echo "<option value>".$row["advisor_name"]."</option>";
What you should do is this:
echo "<option value=".$row["advisor_name"].">".$row["advisor_name"]."</option>";
Additionally, you would not use $selected_insert in the query unless you have munged the variable. Instead, you should probably use $_POST['Advisors'].
Then, to top it all of you should get in the habit of using prepared statements for all of your queries. If not, you're leaving yourself wide open to SQL Injection.
I have two .php pages, one that returns the contents of a table including an id for each entry along with an html text input and another that retrieves the details and allows me to update the record.
I'd like to store the id of the entry by clicking on the list item using a href rather than having to text input the id and submit.
choose.php
echo "<ul>";
while ($row=mysql_fetch_array($result)) {
$reference=$row[reference];
$name=$row[name];
echo "<li>$reference, $name</li>";
}
echo "</ul>";
session_start();
$_SESSION['regName'] = $reference;
mysql_close($link);
?>
<form method="get" action="update.php">
<input type="text" name="regName" value="">
<input type="submit">
</form>
update.php
session_start();
$reference = $_GET['regName'];
echo "Your selection id is: ".$reference.".";
$query="SELECT * FROM firsttable WHERE reference='$reference'";
$result=mysql_query($query) or die("Query to get data from firsttable failed with this error: ".mysql_error());
$row=mysql_fetch_array($result);
$name=$row[name];
echo "<form method=\"POST\" action=\"updated.php\">";
echo "<p>";
echo "<label for=\"name\">Name: </label><input type=\"text\" id=\"name\" name=\"name\" size=\"30\" value=\"$name\"/>";
echo "<p><input type=\"submit\"></p>";
echo "</form>";
I apologise if this seems very obvious, I've only started to learn php as of today and it's much more complicated than anything I've done up until now.
Thanks
James
Answering your question, you just need to use HREF parameter of A tag. This will make an active link, which will contain a reference you need:
echo '<ul>';
while ($row = mysql_fetch_array($result)) {
$reference = $row[reference];
$name = $row[name];
echo '<li><a href=/update.php?regName='.$reference.'>'.$name.'</a></li>';
}
echo '</ul>';
?>
Read here for more details about passing data via GET\POST: https://www.w3schools.com/tags/ref_httpmethods.asp
And as you were told above, please consider rewiring the code as it is totally unsafe and must not be used anyhow besides some very basic concept proof. And only inside intranet or local machine.
Good luck!
So, I have a basic PHP site that brings up a list of salespeople from a MySQL server when a selection from a drop-down box is submitted. I've set up a button to appear next to each result, and I want a php script to run when the button is clicked using MySQL data from that specific result. Everything works except the button that runs the second MySQL query. Here's an example of the table after the first query:
<table border="1">
<tr>
<td>Last name</td>
<td>First Name</td>
<td>Job Title</td>
<td>City</td>
<td>Client List</td>
</tr>
<tr>
<td>Bondur</td>
<td>Gerard</td>
<td>Sale Manager (EMEA)</td>
<td>Paris</td>
<td>
<form method="POST" action="empLookup.php">
<input type="submit" name="empLookup" value="Look up clients"
</td>
</tr>
</table>
By clicking on the button I would run a MySQL command like 'SELECT clients FROM blah WHERE employeeNumber = ?'
I don't have a problem with any of this except passing the value from the button to the PHP script.
This is what my PHP code looks like for handling the form submission and display of results. The button(s) in question are in the HTML table in the foreach loop.
<?php #this is the default php file for looking up Employees
$page_title = 'Our Associates by City';
require ('./pdoConn.php');
$sql = "SELECT DISTINCT city from Offices";
echo '<h1>Our Associates by City</h1>';
Type in a Name to view Years</a><br>';
//create the form
echo 'Please select a year: <br>';
echo '<form action="index.php" method="post">';
echo '<select name= "city">';
foreach($conn->query($sql) as $row)
{
//each option in the drop down menu is each and every year
//brought up by the query
echo '<option value ="'. $row['city'].' ">'. $row['city']. '</option>';
} //end of foreach
echo '</select>'; //end drop down menu
//now to create the submit button
echo '<br><input type="submit" name="submit" value="List"><br>';
echo '</form>'; //end of form
//This if statement runs when the submit button is clicked
if ($_SERVER[REQUEST_METHOD] == 'POST')
{
$flit = $_POST[city]; //the city variable from the HTML form will be used
echo '<br><br>';
$sql2 = "SELECT employeeNumber,lastName,firstName,jobTitle,city
FROM Employees,Offices
WHERE Employees.officeCode = Offices.officeCode AND city = ?";
$stmt = $conn->prepare($sql2);
$stmt->execute(array($flit));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo 'Contact any of our local staff: <br>';
//create a table of employees
echo '<table border="1"><tr><td>Last name</td><td>First Name</td>';
echo '<td>Job Title</td><td>City</td></tr>';
//time to populate the table, this loop runs for each entry
foreach($rows as $r)
{
echo '<tr><td>'.$r[lastName].'</td><td>'.$r[firstName].'</td><td>';
echo $r[jobTitle].'</td><td>'.$r[city].'</td><td>';
echo '<form method="POST" action="empLookup.php">';
//now to make the button which will search the employee's client list
echo '<input type="submit" name="empLookup" value="Look up clients"</td></tr>';
} //end foreach
echo '</table>';
} //end if server request post thing
?>
I does not completely understood your exact requirement but I think you want employee number into your button if this is your requirement then you can simply check this code
`echo '<input type="submit" name="empLookup" value="'.$r['emp_id_from_database'].'"</td></tr>';`
From your html code, your form looks empty.
You need to add the data to your html form. If you want to avoid the user to see you can use fields. Like it was in the comments said, use $variableName instead of ? in your query. Don't forget use \"$variableName\" to avoid mysql injections.
I took a second reading of your code: You realy should read a php book completly before you program stuff for productive company websites. There are beginner mistakes in your code. And some beginner mistakes leads to insecure websites. I hope this doesn't look an offense, but like an advise.
I've been having a rather irritating issue regarding capturing SQL information and then placing it into a PHP form (in theory, it should be kinda easy).
Here's the code for the SQL database information:
<?
$select = "SELECT * FROM beer WHERE country_id = 3";
$data = mysql_query($select) or die("Unable to connect to database.");
while($info = mysql_fetch_array($data)) {
echo '<center>';
echo '<h2>'.$info['name'].'</h2>';
echo '<table style="padding:0px;"><tr>';
echo '<tr><td><b>ABV%:</b></td><td width="570">'.$info['abv'].'</td></tr>';
echo '<tr><td><b>Bottle Size:</b></td><td width="570">'.$info['bottleSize'].'</td></tr>';
echo '<tr><td><b>Case Size:</b></td><td width="570">'.$info['caseSize'].'</td></tr>';
echo '<tr><td><b>Price:</b></td><td width="570">$'.$info['price'].'</td>';
echo '</tr></table>';
echo '</center>';
echo '<br/>';
echo '<img src="" border="0"><br><br>';
echo '<form name="cart" method="post" action="cart.php"> <table border="0"> <tr>';
echo '<td><input type="hidden" name="bname" value="'.$info['name'].'"><input type="hidden" name="price" value="'.$info['price'].'"></td>';
echo '<td><b>Quantity:</b></td>';
echo '<td><input type="text" name="qty" size="3"></td>';
echo '<td><input type="submit" value="Add to Cart" a href="cart.php?name=foo&price=bar" /a></td>';
echo '</tr></table></form>';
}
?>
I want when the submit value is pressed to somehow transmit the price, quantity and name to a basic HTML form (so that all the user has to do is add name, address, etcetc). I am completely stumped on how to do this.
If anyone could help, it would be much appreciated.
As you mentioned Amazon checkout, here is one thing you probably don't understand.
Amazoin doesn't use the form to move items data between server and browser to and fro.
It is stored in a session on a server time. All you need is some identifier put into hidden field.
To use a session in PHP you need only 2 things:
call session_start() function before any output to the browser on the each paghe where session needed.
Use `$_SESSION variable.
That's all.
Say, page1.php
<?
session_start();
$_SESSION['var'] = value;
and page2.php
<?
session_start();
echo $_SESSION['var'];
You wrote that code? because it's simply the same code as here.
You'll need to write an HTML form in your cart.php file
and use the $_POST variable to show the values of the price , quanitity and name.
For example:
<form method='post'>
<input type='text' name='price' value='<?=$_POST['price']?>'>
<input type='text' name='quanitity' value='<?=$_POST['qty']?>'>
i have problem passing data from one page to another using GET, for example
i have these:
<form method=post action=edit.php>
<td><input type=text name=firstname></td>
<td>
<?
$query="SELECT * FROM gender;
$result = mysql_query ($query);
echo "<select name=gender_id>";
while($nt=mysql_fetch_array($result))
{
echo "<option value=$nt[gender_id]>$nt[gender_name]</option>";
}
echo "</select>";
?>
</td>
<td><input type=submit name=edit></td>
</form>
now to pass these to edit.php using GET
if($mode=="edit")
{
$fistname=$_GET["fistname"];
$gender=$_GET["gender_id"];
<td><input type=text name=firstname value="<? echo $fistname; ?>"></td>
Above is a working code for an input type text. I know how to pass values with input type text but my problem is that HOW WOULD I DO THESE WITH A SELECT tag WHICH HAS VALUES FROM A MYSQL DATABASE?.
<?
$query="SELECT * FROM gender;
$result = mysql_query ($query);
echo "<select name=gender_id>";
while($nt=mysql_fetch_array($result))
{
if ($nt[gender_id]==$_POST["gender_id"])
$selected="selected";
else
$selected="";
echo "<option ".$selected."value=$nt[gender_id]>$nt[gender_name]</option>";
}
echo "</select>";
?>
you were using <form method=**post** action=edit.php>, in that way you should use $fistname=$_POST["fistname"]; $gender=$_POST["gender_id"];
if you want to use $fistname=$_GET["fistname"]; $gender=$_GET["gender_id"];
you should use <form method=**get** action=edit.php but in that way, the thoses values will be visible in the url.
You have a typographical error on your edit.php change $_GET['fistname'] to $_GET['firstname']. Then edit:
<form method=post action=edit.php>
and put method="get"
<form method=post action=edit.php method="get">
And to prevent errors on edit.php. Add these:
if ((isset($_GET['firstname']) && (isset($_GET['gender_id'])) {
//your code
} else {
//some error message
}
<form method="GET" action="edit.php">
Or use $_POST in the script instead.
EDIT, since you didn't bother putting your question in the question:
As you iterate through the options, test the value of $nt[gender_id] and add the selected attribute to the one that matches.