I am trying to get a form to input data into my "mysql database" however i am getting an error message and also it is inputting a blank data everytime the page loads.
Here is my code:
<form action="insert.php" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This creates my table layout
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>";
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select examples");
}
// This inserts new information to the Database
$query = "INSERT INTO test1 VALUES('id', '$name')";
$result = mysql_query($query);
if ($result){
echo("Input data is Successful");
}else{
echo("Input data failed");
}
// This chooses which results i want to select from
$result = mysql_query("SELECT `id`, `name` FROM `test1` WHERE 1");
// This outputs the information into my table
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . "[D]" . "</td>";
echo "</tr>";
}
echo "</table>";
// This closes my connection
mysql_close($con);
?>
Here is the error message:
( ! ) SCREAM: Error suppression ignored for
( ! ) Notice: Undefined variable: name in C:\wamp\www\sql_table.php on line 36
Call Stack
Time Memory Function Location
1 0.0006 250360 {main}( ) ..\sql_table.php:0
You are trying to access to the POST data, so you should do something like that :
EDIT: be careful about the data you put into your database. You should use a modern database API, or, at least, escape your data (cf bellow code)
<form action="insert.php" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
// Following code will be called if you submit your form
if (!empty($_POST['name'])) :
// This is the connection to my database
$con = mysql_connect('127.0.0.1', 'shane', 'diamond89');
if (!$con){
die('Could not Connect: ' . mysql_error());
}
// This creates my table layout
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Delete</th>
</tr>";
// This selects which database i want to connect to
$selected = mysql_select_db("shane",$con);
if (!$con){
die("Could not select examples");
}
// This inserts new information to the Database
$query = "INSERT INTO test1 VALUES('id', \'".mysql_real_escape_string($_POST['name'])."\')";
$result = mysql_query($query);
if ($result){
echo("Input data is Successful");
}else{
echo("Input data failed");
}
// This chooses which results i want to select from
$result = mysql_query("SELECT `id`, `name` FROM `test1` WHERE 1");
// This outputs the information into my table
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . "[D]" . "</td>";
echo "</tr>";
}
echo "</table>";
// This closes my connection
mysql_close($con);
endif;
?>
Related
I get an error of Undefined index, what is the reason?
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['CandidateName'] . "</td>";
echo "<td>" . $row['Position'] . "</td>";
echo "<td><input type='radio' name='candidateid' value='".$row['candidateID']."' >";
echo "<td>" . $row['NumberofVotes'] . "</td>";
$candidateid=$row['CandidateID'];
}
Here is the error
Array ( [0] => 1 [CandidateID] => 1 [1] => Jejomar Binay [CandidateName] => Jejomar Binay [2] => President [Position] => President [3] => [NumberofVotes] => ) Array ( [0] => 2 [CandidateID] => 2 [1] => Mar Roxas [CandidateName] => Mar Roxas [2] => President [Position] => President [3] => 1 [NumberofVotes] => 1 )
I will show you now the whole code and the its working now, my output here is to add 1 in number of votes when the radio button is working. it has no error but when i selected the first radio button it only updates the second data.
<html>
<center>
<font size="2" face = "century gothic">
<?php
$con=mysqli_connect("localhost","root","","election2016");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM candidate_info");
echo "<table border='1'>
<tr>
<th>Candidate Name</th>
<th>Position</th>
<th>Vote</th>
<th>Number of Votes</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['CandidateName'] . "</td>";
echo "<td>" . $row['Position'] . "</td>";
echo "<td><input type='radio' name='candidateid' value='".$row['CandidateID']."' >";
echo "<td>" . $row['NumberofVotes'] . "</td>";
$candidateID=$row['CandidateID'];
}
echo "</table>";
mysqli_close($con);
?>
<br>
<br>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<input type="text" name="candidateid" value="<?php echo $candidateID;?>">
<input name = "update" type = "submit" id = "update" value = "update">
</form>
</center>
</font>
</html>
<?php
if(isset($_POST['update'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$candidateid = $_POST['candidateid'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$candidateid = $_POST['candidateid'];
$sql = "UPDATE candidate_info SET numberofvotes = 1 WHERE candidateid = '$candidateid'" ;
mysql_select_db('election2016');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
?>
The field "candidateid" should be integer data type, but you are enclosed this field value with ''(single quotes) in the update query?
$sql = "UPDATE candidate_info SET numberofvotes = 1 WHERE candidateid = '$candidateid'";
if it is an integer datatype then you should remove the single quote
$sql = "UPDATE candidate_info SET numberofvotes = 1 WHERE candidateid = $candidateid";
and in MySQL every field names are case sensitive, so as you told the field names are
candidateid, candidatename, position, numberofvotes
so, you should use these names when you retrieving the values as well
<?php
if(isset($_POST['update'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$candidateid = $_POST['candidateid'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$candidateid = $_POST['candidateid'];
$sql = "UPDATE candidate_info SET numberofvotes = numberofvotes + 1 WHERE candidateid = '$candidateid'" ;
mysql_select_db('election2016');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
?>
<html>
<center>
<font size="2" face = "century gothic">
<?php
$con=mysqli_connect("localhost","root","","election2016");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM candidate_info");
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<?php
echo "<table border='1'>
<tr>
<th>Candidate Name</th>
<th>Position</th>
<th>Vote</th>
<th>Number of Votes</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['candidatename'] . "</td>";
echo "<td>" . $row['position'] . "</td>";
echo "<td><input type='radio' name='candidateid' value='".$row['candidateid']."' >";
echo "<td>" . $row['numberofvotes'] . "</td>";
}
echo "</table>";
mysqli_close($con);
?>
<br>
<br>
<input name = "update" type = "submit" id = "update" value = "update">
</form>
</center>
</font>
</html>
there is no key in your array $row as 'candidateid' please do var_dump($row); and see what is the key name, or if these are just same as your column name in your DB table, check the name of it.
Points To Be Noted :
No Need to create separate <form></form> for sending candidateid for updating numberofvotes.
If you are submitting in same page then avoid multiple database connection.
Your database table candidate_info field name is not matching with what you wrote in <table><tr></tr></table>. So, use exact column name what is there in database table.
Put your complete <table></table> inside <form></form>.
Since you are looking for single candidate value to get get updated, so radio button is helpful. If multiple candidate value need to be updated, then you have to use checkbox with name as array type.
Updated Code:
<html>
<center>
<font size="2" face = "century gothic">
<?php
$con=mysqli_connect("localhost","root","","election2016");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<form method="post" action = "<?php $_PHP_SELF ?>">
<?php
$result = mysqli_query($con,"SELECT * FROM candidate_info");
echo "<table border='1'>
<tr>
<th>Candidate Name</th>
<th>Position</th>
<th>Vote</th>
<th>Number of Votes</th>
</tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['candidatename'] . "</td>";
echo "<td>" . $row['position'] . "</td>";
echo "<td><input type='radio' name='candidateid' value='".$row['candidateid']."' ></td>";
echo "<td>" . $row['numberofvotes'] . "</td>";
$candidateID=$row['candidateid'];
}
echo "</table>";
mysqli_close($con);
?>
<br>
<br>
<input name = "update" type = "submit" id = "update" value = "update">
</form>
</center>
</font>
</html>
<?php
if(isset($_POST['update'])) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$candidateid = $_POST['candidateid'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$candidateid = $_POST['candidateid'];
$sql = "UPDATE candidate_info SET numberofvotes = 1 WHERE candidateid = '$candidateid'" ;
mysql_select_db('election2016');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
mysql_close($conn);
}
?>
I would like to know how can i put the table from mysql in a new file.php.
I want the MySql table to be on the page.
This is my code that inserts data in MySql.
<?php
// Create connection
$con = mysqli_connect("host", "id_", "password", "xxxxxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Task = $_POST['Task'];
$Date = $_POST['Date'];
$Desc = $_POST['Desc'];
$sql = "INSERT INTO tasklist (Task, Date, Description)
VALUES ('$Task', '$Date', '$Desc')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
<html>
<body>
<form action="addtask.php" method="post">
Task: <input type="text" name="Task">
Date: <input type="text" id="datepicker" name="Date">
Decrption:<textarea type="text" name="Desc"></textarea>
<input type="submit" value="submit">
</form>
</body>
</html>
Try this code:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
also u can try w3schools sample code :
Display the Result in an HTML Table
The following example selects the same data as the example above, but will display the data in an HTML table:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The output of the code above will be:
first code comes from "Jonnny" in this article
All the data is loaded into a table, each row as a button. Once the button has been pressed, the row has to be updated. But when I click on the button, nothing happens. The text box on the rows return to its original value... It is really starting to cheese me off
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'dragondrivingschooldb'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='$_POST[txtfirstname]' WHERE BookingID='$_POST[txtid]' "); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT * FROM booking"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form action=EditStudent.php method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name=update type=submit value=update /> </td>"; //once press update row this button is apart of
echo "<td> <input type=text value=" . $row['BookingID'] . " name=txtid /> </td>";
echo "<td> <input type=text value=" . $row['FirstName'] . " name=txtfirstname /> </td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
mysqli_close($con); //Close connection
?>
</html>
I think that BookingID it is an integer, so your update line need to be:
$updatequery = mysqli_query($con, "UPDATE booking SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID=" . $_POST['txtid'] . ""); //excute UpDate Query
EDIT:
I tested your script and the problem was that you closed the form outside the while loop. Now its working
<!DOCTYPE html>
<head>
<title>Edit Students</title>
</head>
<?php
$user = 'root'; //Database username ("Root for xampp")
$pass = ''; //Database password ("empty for exampp")
$db = 'all_tests'; //Name of database
$con = new mysqli('localhost', $user, $pass, $db) or die("Unable to connect"); //Create new data connection ('name of host/server', user, password, database name)
if (isset($_POST['btnUpdate'])) { //Once Update button pressed perform this code
$updatequery = mysqli_query($con, "UPDATE test_1 SET FirstName='" . $_POST['txtfirstname'] . "' WHERE BookingID='" . $_POST['txtid'] . "'"); //excute UpDate Query
};
$sql = mysqli_query($con, "SELECT *FROM test_1"); //Select All from Booking
//Create Headers for table
echo "<table border='1'>
<tr>
<th></th>
<th>Booking ID</th>
<th>First Name</th>
</tr>";
//Show Edit Form///////////////////////////////////////////////////////////////////////////////////////////////////
while($row = mysqli_fetch_array($sql)) { //Run sql code till there are no more rows to import
echo "<form method=post>"; //Run update code at top of this page
//Populate table with query (sql)
echo "<tr>";
echo "<td> <input name='btnUpdate' type='submit' value='update' /> </td>"; //once press update row this button is apart of
echo "<td> <input type='text' value=" . $row['BookingID'] . " name='txtid' /> </td>";
echo "<td> <input type='text' value=" . $row['FirstName'] . " name='txtfirstname' /> </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysqli_close($con); //Close connection
?>
at first check that $_POST[txtid] has value or not. and be sure that field name is correct or incorrect.
There are no input field in your html that has name btnUpdate. What I can see its name is update. Therefore your row:
if (isset($_POST['btnUpdate'])) {
would never be true
I am just unable to understand why the rows are not getting deleted!
please note that i am getting the login values of corrected check boxes in the php page.
from my point of view, most probably error should be in php page where i am using
'DELETE FROM' query.
<?php
session_start();
?>
<html>
<head>
<form id="delete_customers" action="deletecustomers.php" method="post">
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("car_rental_system", $con);
$result = mysql_query("SELECT * FROM customer");
echo "<table border='1' align='center'>
<tr>
<th>first_name</th>
<th>Last_name</th>
<th>login</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['login'] . "</td>";
echo "<td>"."<input type='checkbox' name='deletingcustomers[]'
value=$row['login']}"."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
<p class='submit'>
<button type='submit' name='dscustomer'>Delete selected</button>
</p>
</head>
</html>
//NOW deletecustomers.php
<?php
session_start();
$_SESSION['deletingcustomers'] = $_POST['deletingcustomers'];
$N = count($_SESSION['deletingcustomers']);
$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("car_rental_system", $con);
if(empty($_SESSION['deletingcustomers'])) {
echo("No customers selected");
} else {
for ($i=0; $i<$N; $i++) {
$sql1="delete from `customer`
where login='{$_SESSION[deletingcustomers][$i]}'";
if(mysql_query($sql1,$con))
echo 'executed';
}
}
?>
NO! No! Why do people keep using mysql_query().....(head desk)
Please look up PDO. http://php.net/manual/en/book.pdo.php it helps prevent sql injections and gives you a better understanding of how to harness oop's power.
Your $_SESSION[deletingcustomers][$i] needs to be $_SESSION['deletingcustomers'][$i]
Example on its way
$tempVar = $_SESSION['deletingcustomers'][$i];
$dbConnection = new PDO("mysql:host=".$hostName.";dbname=".$dbName, $username, $password);
$sql = "delete from `customer` where login='$tempVar'";
$stmt = $newObj->prepare($sql);
$stmt->execute();
Replace
echo "<td>"."<input type='checkbox' name='deletingcustomers[]' value=$row['login']}"."</td>";
To
echo "<td><input type='checkbox' name='deletingcustomers[]' value='".$row['login']."'</td>";
and try
Im a newbie in PHP and I want to create a simple webpage app for my website, I was able to produce this page base on a tutorial here.
<?php
$con = mysql_connect("localhost","*****","*****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*****", $con);
$result = mysql_query("SELECT * FROM products");
echo "<table border='1'>
<tr>
<th>Name</th>
<th>classification</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['classification'] . "</td>";
echo "<td><input type='checkbox' name='{number[]}' value='{$row['prodID']}' /></td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
<?php
?>
<html>
<head>
</head>
<form name="form1" method="post" action="result_page.php">
<input type="submit" name="Submit" value="Submit">
</p>
</form>
<body>
</body>
</html>
but my problem is how to create a result_page.php to show the selected entries or data base on the selected checkbox so i can create a comparison page. I have this as being my result_page.php but nothing is showing up. I know Im doing something wrong but I cant find out.
<?php
error_reporting(E_ALL);
$host = 'localhost';
$user = '******';
$pass = '******';
$dbname = '******';
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
mysql_select_db($dbname);
$sql = "SELECT * FROM products WHERE prodID IN (";
foreach ($_POST['number'] as $product) $sql .= "'" . $product . "',";
$sql = substr($sql,0,-1) . ")";
$result = mysql_query($sql);
while ($myrow = mysql_fetch_array($result))
{
echo "<table border=1>\n";
echo "<tr><td>Name</td><td>Position</td></tr>\n";
do {
printf("<tr><td>%s %s</td><td>%s</tr>\n", $myrow["1"], $myrow["2"], $myrow["3"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
}
?>
A quick glance, the section that generates the output is not correct. You have looped two times for no apperant reason.
while ($myrow = mysql_fetch_array($result)) //<========remove this line
{ //<========remove this line
echo "<table border=1>\n";
echo "<tr><td>Name</td><td>Position</td></tr>\n";
do {
printf("<tr><td>%s %s</td><td>%s</tr>\n", $myrow["1"], $myrow["2"], $myrow["3"]);
} while ($myrow = mysql_fetch_array($result));
echo "</table>\n";
} //<========remove this line
This is done by human parse, but should serves as a starting point.
And to recap tadman, no this is not a good tutorial. And normally you won't need to do printf for the output.