How can I update MySQL with PHP, using the following syntax: - php

<?php
//connect to server
$connect = mysql_connect("localhost","name","password");
//connect to db
mysql_select_db("complexm_pondlife", $connect);
//query the db
$query = mysql_query("SELECT * FROM frogs");
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<button onclick="show()">SHOW DATA</button>
<p id="clip"style="visibility: hidden">
<?php
WHILE($rows = mysql_fetch_array($query)):
$name = $rows['name'];
$age = $rows['age'];
$sound = $rows['sound'];
$id = $rows['id'];
?>
<?php
echo $id.") "."Name: ";
?>
<form action = "" method = "post">
<input type="text" id="name" value='<?=$name?>'>
<input type="submit" name="update_db" value="Update">
</form>
<?php
echo "Age: "."$age<br><br>";
echo "Sound: "."$sound<br><br>";
echo "___________<br><br>";
endwhile;
?>
</p>
<?php
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = '$name'");
}
if(isset($_POST['update_db'])){
echo upload();
}
?>
<script>
function show(){
document.getElementById('clip').style.visibility="visible";
}
</script>
This code gives me: Notice: Undefined variable: name in /home1/complexm/public_html/projects.php on line 70
I dont know why though. So if anyone can tell me i would like to know. If the syntax is wrong please tell me!

This answer is based on your original post and not marking it as an edit, should anyone wonder.
The reason why your upload() function is failing, is because you haven't included the mysql_query() function, along with a few missing parts. (Parts, being quotes/brackets).
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = 'TreeFrog'");
}
A word of advice though:
Your present code is open to SQL injection.
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
also or die(mysql_error()) to mysql_query().
Edit:
To fire up your function using a PHP method, I recommend you change the
<input type="submit" onclick="update()"> to
<input type="submit" name="update_db" value="Update"> and wrapping an isset() around it.
I.e.:
<?php
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = 'TreeFrog'");
}
if(isset($_POST['update_db'])){
echo upload();
}
?>
However, you will need <form></form> tags around your form's element(s) and a post method.
<form action = "" method = "post">
<input type="text" id="name" value='<?=$name?>'>
<input type="submit" name="update_db" value="Update">
</form>
Edit #2:
This is a mysqli_ method, please change the DB credentials to match yours if they do not match.
I had to remove the upload() function, it was giving me too much trouble.
A hidden input has been added in the form, which is essential to doing updates like these.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//connect to server
$DB_HOST = 'localhost';
$DB_USER = 'name';
$DB_PASS = 'password';
$DB_NAME = 'complexm_pondlife';
$link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($link->connect_errno > 0) {
die('Connection failed [' . $link->connect_error . ']');
}
//query the db
$query = mysqli_query($link,"SELECT * FROM frogs");
?>
<button onclick="show()">SHOW DATA</button>
<p id="clip"style="visibility: hidden">
<?php
WHILE($rows = mysqli_fetch_array($query)):
$name = $rows['name'];
$age = $rows['age'];
$sound = $rows['sound'];
$id = $rows['id'];
?>
<?php
echo $id.") "."Name: ";
?>
<form action = "" method = "post">
<input type="text" id="name" name="thename" value="<?php echo $name; ?>">
<input type="hidden" name="the_id" value="<?php echo $id; ?>">
<input type="submit" name="update_db" value="Update">
<br>
</form>
<?php
echo "Age: "."$age<br><br>";
echo "Sound: "."$sound<br><br>";
echo "___________<br><br>";
endwhile;
?>
</p>
<?php
if(isset($_POST['update_db'])){
$theid = stripslashes($_POST['the_id']);
$theid = mysqli_real_escape_string($link,$_POST['the_id']);
$thename = stripslashes($_POST['thename']);
$thename = mysqli_real_escape_string($link,$_POST['thename']);
$results= mysqli_query($link, "UPDATE frogs SET name = '$thename' WHERE id = '$theid'");
}
?>
<script>
function show(){
document.getElementById('clip').style.visibility="visible";
}
</script>
You can also redirect to the same page by adding this at the top:
<?php
ob_start();
?>
then adding this after your query:
if($results){
header("Location: http://www.yoursite.com/update_frogs.php");
}

Related

Form is not posting to MySQL database

I am trying to send data from a textfield to my database. When I run the code I get no errors. But the code isnt posting the data to the database. I cant see whats wrong, can someone look what is wrong?
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<button name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
$data_1 = $_POST['data_1'] ;
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>
a) your script needs more error handling.
Before accessing $_POST['data_1'], you should test its existence, e.g. via isset().
Your database code doesn't have any error handling, too. Either set the error mode to PDO::ERRMODE_EXCEPTION or (/and) make sure you test each and every return value of the PDO::* methods.
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
if ( !$stmt ) {
yourErrorHandler('could not prepare statement', $db->error);
}
else if ( !$stmt->execute(array($adres_1)) ) {
yourErrorHandler('could execute statement', $stmt->error);
}
else if ( 1>$stmt->rowCount() ) {
// no record has been updates
}
else {
// at least one record has been updated
}
b) $stmt->execute(array($adres_1)); What is $adres_1? It's not anywhere else in that code.
c) Your code is prone to sql injections. You can fix that e.g. by using prepared statements + parameters.
The whole code looks like small parts of other scripts have been copy&pasted without understanding what those snippets do.
Are you using autocommit? maybe your db changes are being rolled back. Try adding an extra COMMIT SQL statement.
You have to submit your code. Then only the values are send to the php file by the POST method.
index.php
<?php
session_start();
?>
<html>
<form name="reaction" method="post" action="./send/send1.php">
<input type="text" class="form-control" id="data_1" name="data_1" placeholder="Data 1" />
<input type="submit" name="send">Send</button>
</form>
</html>
send1.php
<?php
session_start();
?>
<html>
<body>
<table>
<?php
$correct = true;
if ($_POST['send']) {
$data_1 = $_POST['data_1'] ;
}
?>
</table>
<?php
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "UPDATE table SET data_1=" . $data_1 . " WHERE id='" . $_SESSION['ID'] ."'";
$stmt = $db->prepare($query);
$stmt->execute(array($adres_1));
echo "<br /><br />Success.<br />\n";
} else {
echo "<br /><br />Error.<br />\n";
}
?>
</body>
</html>

PHP: Record is not updating in SQL

My problem is in updating the SQL record. It fetches SQL data into form correctly (For editing) but when I press save edits button it returns following erro inside input field:Notice: Undefined variable: row in C:\xampp\htdocs\edit.php on line 46Please can you tell me how to fix it
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "zz224466";
$database = "zain";
$conn = mysqli_connect($servername,$username,$password,$database);
if($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
if(isset($_GET['edit'])) {
$id = $_GET["edit"]; //Get id of sql table from other php page.
echo $id; //It gives true result. It means that $_GET method above gets id of sql table correctly
$res = mysqli_query($conn, "SELECT * FROM product where product_id=$id");
if ($res == FALSE) {
die("Error");
}
$row = mysqli_fetch_array($res);// Getting row from sql of specific id above selected above
if (isset($_POST['Edit'])) { ///Checking if Edit button has been pressed
$product_category = $_POST['product_category'];
$product_id = $id;
//// SQL query
$sql_category = "UPDATE product SET product_category='$product_category' WHERE product_id=$id";
if (mysqli_query($conn, $sql_category)) {
}
}
}
?>
////////////////////HTML FORM/////////////////////////
<form method="post" action ="edit.php" id="contact-form">
<input type="text" name="product_category" placeholder="product_category" value="<?php echo $row['product_category'];//It prints sql record in input field which is to be updated and it prints correctly. But when I press edit button it gives above mentioned error ?>"/>
<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="Edit" value="Save Edits" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
</div>
</form>
</body>
</html>
Kindly tell me that how to fix it
Try this. Because, when you are pressing submit button. It's going to edit.php with POST value and no GET parameters (after pressing Edit submit button. So, browser is unable to find $id resulting to it, no $row values.)
<input type="text" name="product_category" placeholder="product_category" value="<?php if(isset($row['product_category'])) { echo $row['product_category'];}?>"/>
for example, https:www.example.com/edit.php?edit=1
after pressing submit button, URL changes to
https:www.example.com/edit.php
So, no edit=1
Updated Code
Change your <form> to
<form method="post" action ="edit.php?edit=<?echo $_GET['edit'];?>" id="contact-form">
Additional to what i did before.
Full Updated Code (See lines where i have written Change Here)
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "zz224466";
$database = "zain";
$conn = mysqli_connect($servername,$username,$password,$database);
if($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
if(isset($_GET['edit'])) {
$id = $_GET["edit"];
echo $id;
$res = mysqli_query($conn, "SELECT * FROM product where product_id=$id");
if ($res == FALSE) {
die("Error");
}
$row = mysqli_fetch_array($res);
if (isset($_POST['Edit'])) {
$product_category = $_POST['product_category'];
$product_id = $_GET['edit']; // Change Here
// Changes here
$sql_category = "UPDATE product SET product_category='$product_category' WHERE product_id=$product_id";
if (mysqli_query($conn, $sql_category)) {
}
}
}?>
// Changes here in form tag
<form method="post" action ="edit.php?edit=<?echo $_GET['edit'];?>" id="contact-form">
<input type="text" name="product_category" placeholder="product_category" value="<?php if(isset($row['product_category'])) { echo $row['product_category']; }?>"/>
<div class="btn-group" role="group">
<input type="submit" class="btn btn-default" name="Edit" value="Save Edits" style="margin-top: 15px; margin-right: 15px; border-radius: 4px;">
</div>
</form>
</body>
</html>

Can't get ID to insert into database from HTML Form (using PHP)

Right now I am trying to create a edit form for my forum, and while I CAN get it to edit, it does not insert an ID to the database (rendering it 0 and thus faulty), the ID field have Auto increment and I've double checked it is the primary field. Tried looking over it many times, but there's got to be something I am missing.
The DB connection:
<?php
error_reporting(E_ALL);
session_start();
$host = 'HOSTNAME';
$dbusername = 'USERNAME';
$dbpassword = 'PASSWORD';
$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("<b>Could not connect to database server</b>");
$anslutning->select_db('DATABASE NAME') or die("<b>Could not connect to the specified database</b>");
?>
The form where you edit the post ($edit in this scenario is the ID it grabs when clicking "edit" on a post), as well as where I try to update the database field.
<?php
if(isset($_GET['edit'])) {
// If click on "edit"
$edit = $_GET['edit'];
// The post-editing ID
$getEditData = $anslutning->prepare("SELECT postId, title, content FROM tblPosts WHERE postid='$edit' LIMIT 1");
$getEditData->bind_result($postId, $title, $content);
$getEditData->store_result();
$getEditData->execute();
while($row = $getEditData->fetch()) {
echo '
<div class="editForm">
<form action="index.php" method="POST">
<input type="hidden" name="author" value="'.$_SESSION['loggedIn'].'">
<input type="hidden" name="edit" value="'.$edit.'">
Title: <input type="text" name="new_title" value="'.$title.'"> <br /> <br />
Content: <textarea name="new_content"> '.$content.' </textarea> <br /> <br />
<input type="submit" name="editPost">
</form>
</div>
';
}
}
// Issue(s): Editing a post does not send postId/edit(id) to database
if(isset($_POST['editPost'])) {
$edit = $_GET['edit'];
$author = $_POST['author'];
$new_title = $_POST['new_title'];
$new_content = $_POST['new_content'];
$updatePost = $anslutning->prepare("UPDATE tblPosts SET postId=?, author=?, title=?, content=?");
$updatePost->bind_param("isss", $edit, $author, $new_title, $new_content);
$updatePost->execute();
echo 'Post updated. Redirecting..';
sleep(1);
echo '<script> window.location.href = "index.php?forum=1" </script>';
}
?>
Change
$edit = $_GET['edit'];
to
$edit = $_POST['edit'];

How to edit table values in MySQL and PHP?

I have that people can add team names to my MySQL table. Now I want them to edit it. I have tried several tutorials but i can't figure it out. I like to know what i am doing wrong.
This is my admin.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if(isset($_POST['team'])){
$team = $_POST['team'];
$ID = $_POST['id'];
$query = mysql_query("SELECT * FROM e2teams WHERE Team='$team' and ID='$ID'");
if(mysql_num_rows($query) > 0 ) { //check if there is already an entry for that username
echo "$team bestaat al!";
}
else{
mysql_query("INSERT INTO e2teams (Team) VALUES ('$team')");
header("location:e2admin.php");
}
}
mysql_close();
?>
<html>
<body>
<h1>Add teams</h1>
<form action="e2admin.php" method="POST">
<input type="text" name="team" placeholder="Team naam" /><br>
<input type="submit" value="Toevoegen" />
</form>
<?php
$table = "e2teams";
$sql = "SELECT * FROM e2teams";
$result = mysql_query($sql, $dbhandle);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)) {
echo $row['Team']. "<a href='edit.php?edit=$row[1]'>Bewerk</a><br>";
}
}
?>
</body>
</html>
The add teams works. but the edit button doesn't work yet. If I click on edit I go to the edit.php page; here I want to add the new name and need the Team to change in the MySQL row.
This is my edit.php:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
if( isset($_GET['edit'])) {
$id = $_GET['edit'];
$res = mysql_query("SELECT * FROM e2teams");
$row= mysql_fetch_array($res);
}
if (isset ($_POST['nieuwenaam'])) {
$newname = $_POST['nieuwenaam'];
$id = $_POST['id'];
$sql = "UPDATE e2teams SET Team='$newname' WHERE id='$id'";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php'>";
}
?>
<html>
<body>
<form action="edit.php" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"s" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
I also like to know how to delete team names but this is maybe for a next question.
This should work:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$id = intval($_GET['edit']);
if($id > 0) {
$res = mysql_query("SELECT * FROM e2teams WHERE `id` = $id");
$row= mysql_fetch_array($res);
$newname = mysql_real_escape_string($_POST['nieuwenaam']);
if (!empty($newname)) {
$sql = "UPDATE e2teams SET Team='$newname' WHERE id=$id";
$res = mysql_query($sql) or die ("Fout bij updaten".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=edit.php?edit=$id'>";
}
}
?>
<form action="edit.php?edit=<?= $id; ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" /><br>
<input type="submit" value="Update" />
</form>
</body>
</html>
Edit: Also, about the intval() and mysql_real_escape_string(). Since you were using $_GET without any filter, I've added intval() function on it. Without filtering $id you could've been easily attacked by some sort of e.g. SQL Injection. Same with mysql_real_escape_string(). You might read about this filter function in php manual. For further study I recommend changing mysql_ functions to PDO or mysqli prepared statements. Happy coding!
Check your edit form. You have to put the value attribute like this value="s" no like value"". I think thats all.
I assume when they click on the edit link it's passing the id of the team so the edit.php select should be something like:
$id = (int)$_GET['edit'];
if (!empty($id))
{
$sql = "SELECT * FROM e2teams WHERE id='$id'";
$result = mysqli_query($sql);
$row = mysql_fetch_assoc($res);
}
//... keep the rest of code as is
Now you need to change the HTML form to:
<form action="edit.php?edit=<?php echo $row['id'] ?>" method="POST">
<input type="text" name="nieuwenaam" placeholer="test" value="<?php echo $row['Team'] ?>" /><br>
<input type="hidden" name="id" placeholder="idnaam" value"<?php echo $row['id'] ?>" /><br>
<input type="submit" value="Update" />
</form>

jQuery not receiving part of data

I'm creating testing application for sending and receiving messages using PHP/jQuery and AJAX. My code works with no problems when I comment out this part of code:
$("#sendUser").submit(function(){
return false;
});
If I leave this part uncommented then jQuery don't receive value from <select> tag. Can someone tell me how to solve this. This is my full code:
<form action="send_toUser.php" method="post" id="sendUser">
<label>Title: </label>
<input type="text" name="title" id="title"><br>
<label>To: </label>
<select name="user" id="user">
<?php $getData = $mysqli->query("select * from login");
while($row = $getData->fetch_assoc()):
?>
<option><?php echo $row['username']; ?></option>
<?php endwhile; ?>
</select><br>
<label>Message:</label><br>
<textarea name="content" id="content"></textarea><br>
<input type="submit" value="Send" id="sendToUserButton">
<label id="outputLabel" hidden></label>
</form>
send_toUser.php
<?php
session_start();
include 'functions.php';
protect();
$title = $_POST['title'];
$content = $_POST['content'];
$user = $_POST['user'];
$con = new mysqli("localhost", "root", "alen", "loginregister") or die($con->error);
$queryReceiver = $con->query("select * from login where username = '$user'");
$idReceiver = $queryReceiver->fetch_assoc();
$idReceiver = $idReceiver['user_id'];
$queryUser = $con->query("select * from admin where username='admin'");
$idUser = $queryUser->fetch_assoc();
$idUser = $idUser['id_admin'];
date_default_timezone_set('UTC');
$date = date('Y-m-d');
$con->query("insert into message values('', '$idReceiver', '$idUser', '$title', '$content','', '$date')") or die("Error while sending!");
echo "Message sent";
?>
script.js
$("#sendToUserButton").click(function(){
$.post("send_toUser.php"),
{"title" : ("#title").val(), "user" : ("#user").val(), "content" : ("#content").val()},
function(data){
$("#outputLabel").html(data);
}
});
$("#sendUser").submit(function(){
return false;
});

Categories