Having trouble getting my mysql table to update - php

This is the form I use to edit my table:
<?php
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database...
$sql = "SELECT * FROM chart WHERE id='$id'";
$result = $conn->query($sql);
// Output the loop...
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { ?>
<form action="./include/update.php" method="post">
<tbody>
<tr>
<td><input type="date" id="date" name="date" value="<?php echo $row['date']; ?>" /></td>
<td><input type="text" id="nuvolog_am" name="nuvolog_am" value="<?php echo $row['nuvolog_am']; ?>" /></td>
<td><input type="text" id="nuvolog_noon" name="nuvolog_noon" value="<?php echo $row['nuvolog_noon']; ?>" /></td>
<td><input type="text" id="nuvolog_pm" name="nuvolog_pm" value="<?php echo $row['nuvolog_pm']; ?>" /></td>
<td><input type="text" id="predisone" name="predisone" value="<?php echo $row['predisone']; ?>" /></td>
<td><input type="text" id="norvase" name="norvase" value="<?php echo $row['norvase']; ?>" /></td>
<tr>
<td colspan="17"><input type="text" id="symptoms" name="symptoms" value="<?php echo $row['symptoms']; ?>" /></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="17"><input type="submit" value="Add Records"></td>
</tr>
</tfoot>
</form>
<? }
} else {
echo "0 results";
}
// Close the connection...
mysqli_close($link);
?>
And this is the update.php
<?php
// Database credentials...
$servername = "localhost";
$username = "...";
$password = "...";
$dbname = "...";
// Database connection...
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection...
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// update data in mysql database
$sql="UPDATE chart SET
id = '$id',
date = '$date',
nuvolog_am = '$nuvolog_am',
nuvolog_noon = '$nuvolog_noon',
nuvolog_pm = '$nuvolog_pm',
predisone = '$predisone',
norvase = '$norvase'
WHERE id='$id'";
$result=mysql_query($sql);
// When chart is submitted...
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close the connection...
mysqli_close($link);
?>
It's probably something very simple, but I cannot figure out why this won't update the records database. I'm hoping somebody can help me figure this out.

Please replace $result=mysql_query($sql); to mysqli code.
like
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
$conn->query($sql);

to run query use this
$conn->query($sql);

You are updating the table using $result=mysql_query($sql); while to connect you used $conn = new mysqli($servername, $username, $password, $dbname);
By the way you should delete this question (if it's possible) or change all your passwords if the password that appears in the old version is used for other accounts too (you can see the edit history).

Related

How can i insert html table data into sql database using php?

This is my table html code. I tried sending the data using the normal insert but it only sends the last row data. I don't know how to send the full data . Can someone please help me with this.
<form action="admin_schedule_employee.php" id="schedule_employee" method="post" >
<input type="date" class="input-sm" name="scheduledate" style="margin:10px;">
<table class="table-responsive table table striped table-bordered">
<thead>
<tr>
<th style="width:20%">Employee First Name</th>
<th style="width:20%">Employee ID</th>
<th style="width:20%">Start Time</th>
<th style="width:20%">End Time</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)): ?>
<tr>
<td><input disabled name="employeename" type="text" value="<?php echo $row['fname']; ?>"></input></td>
<td><input disabled name="employeeid" type="number" value="<?php echo $row['employee_id']; ?>"></input></td>
<td><input name="starttime" type="time"></td>
<td><input name="endtime" type="time"></td>
</tr>
<?php endwhile; ?>
</thead>
<tbody>
</tbody>
</table>
<input type="submit" name="Schedule" value="Schedule">
</form>[This is how my table look like i want to send the whole data to sql database using php][1]
To start with, you will need to create multiple pages:
form.php
process.php
done.php
Creating your user form is simple, place the table in form tags like you have done above, here is an example. Save this page as form.php
<form id="new record" action="process.php" method="POST">
<table width="500px">
<tr>
<td width="50%">
<input type="text" name="fname" id="fname">
</td>
<td width="50%">
<input type="text" name="lname" id="lname">
</td>
</tr>
<tr>
<td width="50%">
</td>
<td width="50%">
<input type="submit" value="Add Record">
</td>
</tr>
</table>
</form>
Next, you will need to create a page which can process this data, and add it to your mysql database. For the following example, I have omitted my database details and substituted them, but you should add your own.
For this example, imagine my database has a table with only an fname and an lname column.
<meta http-equiv="refresh" content="0; url=/done.php" />
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
$fname = $_GET['fname'];
$lname = $_GET['lname'];
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO online (fname, lname)
VALUES ('$fname', '$lname')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record inserted";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Hopefully, that will work to insert the record. Now we need a table on the done.php page which can display all the records in the database. Use the following code:
<html lang="en">
<head>
<meta http-equiv="refresh" content="5; url=/done.php" />
<meta charset="utf-8" />
<title></title>
</head>
<body>
<?php
$servername = "your_server_name";
$username = "mysql_username";
$password = 'mysql_password';
$dbname = "database_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from table_name";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["fname"]. ": ";
echo $row["lname"]. "<br /><br />";
}
} else {
echo "No messages";
}
mysqli_close($conn);
?>
</body>
</html>
Hopefully this will work for you.

Load data from MySQL database to HTML textboxes

I am still learning, can anyone help me, What wrong in my code?
I need to load when you click on the Load button program will search the database ID selected in the dropdown, and them bring the name .. etc and show it on textbox.
Sorry, for my English.
<?php
$servername = "localhost";
$username = "estgv15592";
$password = "estgv155922016";
$dbname = "estgv15592";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["loadbtn"]))
{
$id = (integer) $_POST["id"];
$query = "SELECT NOME, MORADA, PRECO FROM FICHA_DE_OBRA WHERE ID_FICHAOBRA = '$id' ";
$result = mysqli_query($conn, $query);
$details = mysql_fetch_array($result);
$nome = $details["NOME"];
$morada = $details["MORADA"];
$preco = $details["PRECO"];
}
$sql = "SELECT * FROM FICHA_DE_OBRA";
$result = mysqli_query($conn, $sql);
echo '<form id="form" method="post">';
echo "<select name ='id'>";
echo "<option value=''>Selecione Número ficha Obra</option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['ID_FICHAOBRA'] . "'>" . $row['ID_FICHAOBRA'] . "</option>";
}
echo "</select>";
$conn->close();
?>
<input type="submit" value="Load" name="loadbtn">
<table width="300" border="0">
<tr>
<td>Name</td>
<td><input type="text" name="upName" style="text-align:right" value="<?php echo $nome;?>"/></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="upCost" style="text-align:right" value="<?php echo $morada;?>" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="text" name="upActive" style="text-align:right" value="<?php echo $preco;?>" /></td>
</tr>
</table>
</div>
<br/>
</form>
You are not using proper php tag: (e.g. <?php echo $preco;?>):
<tr>
<td>Name</td>
<td><input type="text" name="upName" style="text-align:right" value="<?php echo $nome; ?>"/></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="upCost" style="text-align:right" value="<?php echo $morada; ?>" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="text" name="upActive" style="text-align:right" value="<?php echo $preco; ?>" /></td>
</tr>
Use mysqli_query and mysqli_fetch_array function and note that first argument in mysqli_query should be the connection object where you made the mistake:
$result = mysqli_query($conn, $query); // first PHP block
$result = mysqli_query($conn, $sql); // second PHP block
$details = mysqli_fetch_array($result); // first PHP block
$row = mysqli_fetch_array($result) // second PHP block
And move below lines to the top of your first PHP block, or $conn would be undefined in your first PHP block:
$servername = "localhost";
$username = "estgv15592";
$password = "your_password";
$dbname = "estgv15592";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
The problem is came from your connection to database you use mysqli in connection but you when call queries you use mysql.
This is the code
<?php
$servername = "localhost";
$username = "estgv15592";
$password = "********";
$dbname = "estgv15592";
$conn = mysql_connect($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["loadbtn"]))
{
$id = intval($_POST["id"]);
$query = "SELECT NOME, MORADA, PRECO FROM FICHA_DE_OBRA WHERE ID_FICHAOBRA = '$id' ";
$result = mysql_query($query, $conn);
$details = mysql_fetch_array($result);
$nome = $details["NOME"];
$morada = $details["MORADA"];
$preco = $details["PRECO"];
}
?>
<?php
$sql = "SELECT * FROM FICHA_DE_OBRA";
$result = $conn->query($sql);
echo '<form id="form" method="post">';
echo "<select name ='id'>";
echo "<option value=''>Selecione Número ficha Obra</option>";
while($row = mysqli_fetch_array($result))
{
echo "<option value='" . $row['ID_FICHAOBRA'] . "'>" . $row['ID_FICHAOBRA'] . "</option>";
}
echo "</select>";
$conn->close();
?>
<input type="submit" value="Load" name="loadbtn">
<table width="300" border="0">
<tr>
<td>Name</td>
<td><input type="text" name="upName" style="text-align:right" value="<? echo $nome; ?>" /></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="upCost" style="text-align:right" value="<? echo $morada; ?>" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="text" name="upActive" style="text-align:right" value="<? echo $preco; ?>" /></td>
</tr>
</table>
</div>
<br/>
</form>
</body>
</html>
</div>
this method you use to get data not secure. I advise you to learn pdo or prepared statement with mysqli

adding record to MYSQL database wont work in PHP

Ive written PHP code to add a record to my database. When I click on the save button, then it should say "saved successfully", But all that happens is that the page refreshes with no added records in the database and no "saved successfully" message pops up.
My database connection works properly. So I cant figure out what the problem could be.
here is the PHP code:
<?php
error_reporting(0);
$con = mysqli_connect("localhost", "root", "password") or die("error");
if($con) {
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"])) {
$sql = mysqli_query("INSERT INTO member (memberID, firstName, surname, contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql) {
echo "save successfully";
}
}
?>
here is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ViewMembers</title>
</head>
<body>
<form action="" method="post">
<table style="border:1 #F00 solid;width:500px;overflow:auto;margin:auto;background:#999;">
<tr>
<td>Member ID</td>
<td><input type="text" name"memberID" /></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name"firstName" /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name"surname" /></td>
</tr>
<tr>
<td>Contact Details</td>
<td><input type="text" name"contactDetails" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" name="save" /></td>
</tr>
</table>
</form>
</body>
</html>
You didn't add $conn as parameter of mysqli_query function.See usage :
http://www.w3schools.com/php/func_mysqli_query.asp
<?php
error_reporting(0);
$con = mysqli_connect("localhost","root","password") or die("error");
if($con)
{
mysqli_select_db("maplibrary",$con);
}
if (isset($_POST["save"]))
{
$sql = mysqli_query($con, "INSERT INTO member
(memberID,firstName,surname,contactDetails)
VALUES('{$_POST['memberID']}',
'{$_POST['firstName']}',
'{$_POST['surname']}',
'{$_POST['contactDetails']}'
)");
if ($sql)
{
echo "save successfully";
}
}
?>
Try this one:
<?php
$servername = "localhost";
$username = "username";//YOUR USER NAME!
$password = "password";//YOUR PASSWORD!
$dbname = "myDB"; //YOUR DB NAME!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["save"])){
$var1 = $_POST['memberID'];
$var2 = $_POST['firstName'];
$var3 = $_POST['surname'];
$var4 = $_POST['contactDetails'];
$sql = "INSERT INTO member(memberID,firstName,surname,contactDetails)
VALUES ('".$var1."', '".$var2."', '"$var3."', '"$var4."')";
if ($conn->query($sql) === TRUE) {echo "successfully saved";}
else {echo "Error: " . $sql . "<br>" . $conn->error;}
}
$conn->close();
?>
hope i understood your problem... :)
BTW i suggest you to create a php file that will contain only the connection, because you may will need to connect to the database again in some point so you do not want to copy your code again and again...
so you can create a connect.php that will contain only the connection lines, you can include it (connect.php) inside of any page you want. it will make kit much easier.
look at: php include

How do I update a specific row in a table using php form?

Please bear with me, I'm not familiar yet with the language. I have a table that lists an applicant record such as applicant number, name and status. I want to update an applicant status either 'hired' or 'failed' on a specific row using a PHP form. However, I'm not sure how to get the specific submit name on its row upon submission. Or if you have a workaround I would appreciate that. Thank you so much for your help.
<!DOCTYPE html>
<html>
<h2>Applicant Records</h2>
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password ="";
$mysql_database = "applicantrecord";
// Create connection
$conn = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqli = "SELECT id, firstname, lastname, status FROM applicant";
$result = $conn->query($sqli);
if ($result->num_rows > 0) { ?>
<table class="table">
<thead>
<tr>
<th>Applicant No.</th>
<th>Lastname</th>
<th>Firstname</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<?php
// output data of each row
echo "<tbody>";
while($row = $result->fetch_assoc())
{ ?>
<tr>
<td>
<?php echo $row["id"];
$appid = $row["id"];
?>
</td>
<td>
<?php echo $row["lastname"]; ?>
</td>
<td>
<?php echo $row["firstname"]; ?>
</td>
<td>
<?php echo $row["status"]; ?>
</td>
<td>
</td>
<td>
<div>
<form action="" role="form" method="post" name="form<?php echo $appid; ?>">
<select name="applicant_status">
<option value="Hired">Hire</option>
<option value="Failed">Fail</option>
</select>
</p>
<button type="submit" class="btn btn-default" name = "submit<?php echo $appid; ?>" data-dismiss="modal">Submit</button>
</form>
<?php
if(isset($_POST["submit"])){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$newappid = $appid;
$newapptstatus = $_POST['applicant_status'];
$connect = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $connect ) {
die('Could not connect: ' . mysql_error());
}
$sql_sub = "UPDATE applicant ". "SET status = '$newappstatus'".
"WHERE id = '$newappid'" ;
mysql_select_db('applicantrecord');
$retval = mysql_query( $sql_sub, $connect );
if(! $retval ) {
die('Could not update data: ' . mysql_error());
echo "<script type= 'text/javascript'>alert('An error occured! Applicant status update failed!');</script>";
}
echo "<script type= 'text/javascript'>alert('Applicant status updated successfully!');</script>";
mysql_close($connect);
}
?>
</div>
</td>
</tr>
<?php }
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</html>
In your if statement where you check that $_POST['submit'] is set, the index 'submit' does not exist. Thus isset($_POST['submit']) evaluates to false and your query to update the table is never being executed.
The variable $appid is being changed with each row that is added, so when the page is done loading and the submit button is pushed on a certain row, $appid won't necessarily contain the correct row number.
To get around this, you could use a hidden input in your form:
<input name="id" value="<?php echo $appid ?>" type="hidden">
Then you can replace isset($_POST['submit']) with isset($_POST['id']) and set $newappid = $_POST['id'] to get the row number to be changed.

PHP MySQL Statements not Updating Database

After much editing and checking tutorial sites. Code currently not calling info from Database and when clicking Approve button, does not edit database. I do have a column identifier named Reg_ID which can specify which column of data you choose to edit. The form is submitting, just clears the information that I enter in and doesn't store the data.
This file is named Approve Deny Prayer Request.
<?php
$DB_HOST = "XXXXXXX";
$DB_NAME = "XXXXXXX";
$DB_PASS = "XXXXXXX";
$DB_USER = "XXXXXXX";
$link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($link->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$query = "SELECT * FROM Request";
$result = mysqli_query($link,$query); //<----- Added link
$row = mysqli_fetch_array($result);
if(isset($_POST['add'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$firstname = mysqli_real_escape_string($link,$_POST['first']);
$lastname = mysqli_real_escape_string($link,$_POST['last']);
$phone = mysqli_real_escape_string($link,$_POST['phone']);
$query2=mysqli_query($link,"UPDATE Request SET Reg_F_Name='$firstname', Reg_L_Name='$lastname',Reg_Request='$phone' WHERE id='$id'" );
if($query2){
header("Location: fbcaltusprayerorg.ipagemysql.com");
}
} // brace if(isset($_POST['add']))
?>
<form action="" method="post">
<table>
<input type="hidden" name="id" value="<? echo "$row[Reg_ID]" ?>">
<tr>
<td>First Name:</td>
<td><input type="text" name="first" value="<? echo "$row[Reg_F_Name]" ?>"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="last" value="<? echo "$row[Reg_L_Name]" ?>"></td>
</tr>
<tr>
<td>Prayer Request:</td>
<td><input type="text" name="phone" value="<? echo "$row[Reg_Request]" ?>"></td>
</tr>
</table>
<input name="add" type="submit" id="add" value="Approve Prayer Request">
</form>
Firstly, your initial code did not contain an opening <form> tag; that has been included below.
The way you're attempting to run your code is leaving you open to SQL injection.
Use prepared statements, or PDO
Now, here's what you need to do.
Create a column named id and set it to AUTO_INCREMENT if needed, but not required; just as long as there is some data related to it and holds a unique name/id.
Create a hidden field called/named id
Then use UPDATE along with SET and a WHERE clause.
Sidenote: This will automatically redirect you to the page's filename you've called it.
In this example, I used header("Location: http://www.example.com/update.php");
Replace the DB credentials with your own.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($link->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$query = "SELECT * FROM Request";
$result = mysqli_query($link,$query); //<----- Added link
$row = mysqli_fetch_array($result);
if(isset($_POST['add'])){
$id = mysqli_real_escape_string($link,$_POST['id']);
$firstname = mysqli_real_escape_string($link,$_POST['first']);
$lastname = mysqli_real_escape_string($link,$_POST['last']);
$phone = mysqli_real_escape_string($link,$_POST['phone']);
$query2=mysqli_query($link,"UPDATE Request SET Reg_F_Name='$firstname', Reg_L_Name='$lastname',Reg_Request='$phone' WHERE id='$id'" );
if($query2){
header("Location: http://www.example.com/update.php");
}
} // brace if(isset($_POST['add']))
?>
<form action="" method="post">
<table>
<input type="hidden" name="id" value="<? echo "$row[id]" ?>">
<tr>
<td>First Name:</td>
<td><input type="text" name="first" value="<? echo "$row[Reg_F_Name]" ?>"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="last" value="<? echo "$row[Reg_L_Name]" ?>"></td>
</tr>
<tr>
<td>Prayer Request</td>
<td><input type="text" name="phone" value="<? echo "$row[Reg_Request]" ?>"></td>
</tr>
</table>
<input name="add" type="submit" id="add" value="Approve Prayer Request">
</form>
where is the call to update the database with your sql statement?
I have a function that normally I just for update of the database. I also make sure to add column for each table like UpdateDtTm and add that to the end of my update. That way you know you are going to always update something on an update statement. Also make sure to use a key and a unique id to make sure you only update the row you want.
Also, try using this syntax
$query2 = "Update Request set Reg_F_Name = $row[Reg_F_Name], Reg_L_Name = $row['Reg_L_Name], Reg_Request = $row['Reg_Request'], UpdateDtTM = Now() where <A UNIQUE KEY ROW> = <UNIQUE ID>.
$result = db_update ("updating request in some location", $sql,"update");
function db_update($function_name,$sql,$type) {
// Get access to PHP global variables
global $database;
//if the database value is not pulled from the global array make sure
//the system has it based on the Session value set on load
if (! $database) {
$database = $_SESSION['database'];
}
// Now authenticate the user with the database
$db = db_connect($database);
// Run SQL Query
mysql_query($sql);
// Mysql won't return a $result for UPDATE, so have to test with mysql_affected_rows
// mysql also won't do an update if the values are the same, so you could
// possibly have an instance where nothing is change and this fails
// got around this by adding an updated column that is increased by 1 everytime
// an update is performed. this ensures that you always have something updated
if ( mysql_affected_rows()==0 ) {
// Unable to update
$error = "db_update error<br>$sql<br>".mysql_errno()." - ".mysql_error();
database_error($error,$sql);
// Exit the function after error
exit;
}
// Do nothing for this guy
// We don't need to return anything
return;
}

Categories