I have to following form
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM novinky";
$result = mysqli_query($connection, $sql);
echo "<div id='newsbox'>";
while($zaznam = mysqli_fetch_row($result)):
echo "<form class='newsholder'>";
echo "<input id='displaynadpis' value='$zaznam[1]'>";
echo "<input id='displaybold' value='$zaznam[2]'>";
echo "<textarea id='displaytext'>$zaznam[3]</textarea>";
echo "<div class='buttonsholder'>";
echo "<button class='deletebutton'>Smazat</button>";
echo "<button class='updatebutton'>Upravit</button>";
echo "<input id='prime' type='hidden' attr='id' value='$zaznam[0]'>";
echo "</div>";
echo "<div class='clearfix'></div>";
echo "</form>";
endwhile;
echo "</div>";
mysqli_close($connection);
that displays data from the database in order to update them upon the .updatebutton click.
The data is passed by jquery ajax
$('.updatebutton').on('click', function(){
var idVal = $(this).closest('.newsholder').find('#prime').val();
var displaynadpisVal = $(this).closest('.newsholder').find('#displaynadpis').val();
var displayboldVal = $(this).closest('.newsholder').find('#displaybold').val();
var displaytextVal = $(this).closest('.newsholder').find('#displaytext').val();
alert(displaynadpisVal);
$.ajax({url:"updaterecord.php",
type:"POST",
cache:false,
data:{id: idVal, displaynadpis: displaynadpisVal, displaybold: displayboldVal, displaytext: displaytextVal}
}); });
to the php script
$connection = mysqli_connect(SQL_HOST, SQL_USERNAME, SQL_PASSWORD, SQL_DBNAME) ;
if (mysqli_connect_errno($connection))
{
echo "Nespojeno s MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
$updatenadpis = $_POST['displaynadpis'];
$updatetextbold = $_POST['displaybold'];
$updatetext = $_POST['displaytext'];
echo $updatetext;
$sql = "UPDATE novinky SET nadpis='$updatenadpis',
textbold='$updatetextbold',
text='$updatetext'
WHERE id = '$id'"
;
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
die('Could not enter data: ' . mysqli_connect_error());
}
echo "Entered data successfully\n";
mysqli_close($connection);
to update the database. The problem is, that it only works sometimes, but in about 70% of cases it doesn't make any change. The data is stored in js variables just fine, when tested by alert(), they exist everytime. So the problem must be in the mysqli_query() possibly? Or the AJAX method? I have tried a lot of options and recommendations from other posts but no luck. Thanks for your help...
Biggest problem here is fact that you are passing raw user input to query. Assigning it to variable doesn't change anything!
You should filter everything received from user and use prepared statements to be sure that you are safe.
Also don't use mysqli_connect_error() to check query errors. Use mysqli_error().
Related
I have cleaned my code a little to have the following as my form. But I'm having trouble sending the data and Updating from the new update.php. The form works ok retrieving the data and displaying it. But on submission I get the ok update message but the record isn't changed in the database any ideas.
index.php
<?php
include 'connectdb.php';
// include 'query.php';
$sql = "SELECT id, WeightorMeasure FROM weightsmeasures";
$result = $conn->query($sql)
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<form action=\"update.php\"method=\"post\">";
echo "<input type=\"text\" name=\"id\" value = ".$row["id"].">";
echo "<input type=\"text\" name=\"WeightorMeasure\" value = ".$row["WeightorMeasure"] .">";
echo "<input type=\"submit\" value=\" Submit \" name=\"Update\">";
}
echo "</form>";
} else {
echo "0 results";
}
$conn->close();
?>
update.php
<?php
include 'connectdb.php';
$wm = $_POST['id'];
$id = $_POST['WeightorMeasure'];
$sql = "UPDATE weightsmeasures SET WeightorMeasure='$wm' WHERE id='$id'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
$conn->close();
?>
Have changed to Below and now get this error.
Error updating record: Unknown column 'sdada' in 'field list'. So it looks like its trying to use the form value $wm as a column header in the table rather than the input value.
$wm = $_POST['WeightorMeasure'];
$id = $_POST['id'];
$sql = "UPDATE weightsmeasures SET WeightorMeasure=$wm WHERE id=$id";
$wm = $_POST['id'];
$id = $_POST['WeightorMeasure'];
Maybe you have these the wrong way round? :D
$wm = $_POST['WeightorMeasure'];
$id = $_POST['id'];
By the way your query is vuln to MySQL injection, please consider using prepared statements
You realize that you switched your ID and WeightOrMeasure in the variable assignments from your $_POST data?
This results in an update query that can't find the ID but does not run into a problem. Thus telling you that the operation was successful
I figure out following possible problem in your code.
mysqli_query($conn, $sql); //should be $conn->query($sql);
and this line
$wm = $_POST['id']; //$_POST['WeightorMeasure'];
$id = $_POST['WeightorMeasure'];//$_POST['id'];
the order is wrong. I hope you already have $conn object created in dpconnect.php file.
Ok found the problem was a mixture of the above having $_POST["WeightorMeasure"]; and $_POST["id"]; mixed up but the most important factor was that the table I was posting from contained Multiple Rows and on _POST to update.php it didn't know what to do with all the different rows as the SQL was only dealing with one row. Once I sent single rows through the post it worked fine. Now to learn and add prepared statements as suggested.
update.php
<?php
include 'connectdb.php';
$wm = $_POST["WeightorMeasure"];
$id = $_POST["id"];
echo $wm . "<br>";
echo $id . "<br";
$sql = "UPDATE weightsmeasures SET WeightorMeasure=\"$wm\", id=
$idWHERE id= $id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
$conn->close();
?>
Manual single entry.
index.php
<?php
include 'connectdb.php';
// include 'query.php';
$sql = "SELECT id, WeightorMeasure FROM weightsmeasures WHERE id=11";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<form action=\"update.php\"method=\"post\">";
echo "<input type=\"text\" name=\"id\" value = ".$row["id"].">";
echo "<input type=\"text\" name=\"WeightorMeasure\" value = ".$row["WeightorMeasure"].">";
echo "<input type=\"submit\" value=\" Submit \" name=\"Update\">";
}
echo "</form>";
} else {
echo "0 results";
}
$conn->close();
?>
as the title states I am trying to write a code that will update a boolean data in column (I called 'status') for a specific row. I used while loop in table to display the rows of new registered and where the status is NULL, I've put two buttons (accept, reject) each in td so they'll be displayed to each name, What I want is when the accept button clicked, it sets the status of its row in the table to 1, and when reject is clicked, same thing but sets 0 instead of 1.
I've did a lot of research over this but hit a road block after road block, so I really hope your help in this, many thanks!
Here is my code:
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc".$i."'>Accept</button></td>";
echo "<td><button name='sRej".$i."'>Reject</button></td>";
echo "</tr>";
$i++;
}
if (isset($_POST['sAcc'.$i])) {
$row['status'] = 1;
}
}
getStudent();
?>
</table>
First of all, you miss <form> element. Your form inputs are useless without it, or without ajax.
Secondly, your $_POST check will only check last item. Since after you exit loop $i is set to last value in the loop. So your example will only work on last item.
<button> will now send $_POST with one of indexes sAcc or sRej. And it's value will be ID of your entry.
<table id="sHold" style="border:none;">
<form method="post" action="">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table WHERE status IS NULL;";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['student_name'];
echo "<tr id='sNew".$i."'>";
echo "<td>".$i." - </td>";
echo "<td>{$sId}</td>";
echo "<td>{$sName}</td>";
echo "<td><button type='submit' name='sAcc' value='{$sId}'>Accept</button></td>";
echo "<td><button type='submit' name='sRej' value='{$sId}'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
if (isset($_POST['sAcc']) && intval($_POST['sAcc'])) {
$user_id = (int) $_POST['sAcc'];
// Do the database update code to set Accept
}
if (isset($_POST['sRej']) && intval($_POST['sRej'])) {
$user_id = (int) $_POST['sRej'];
// Do the database update code to set Reject
}
getStudent();
?>
</form>
</table>
Tip: I assume you're beginner. I remade your code. But you dont need to put this code into function. Use functions to handle data retrieval for example. Dont use it to display html.
<table id="sHold" style="border:none;">
<?php
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
function getStudent () {
global $conn;
$query = "SELECT * FROM student_table where status='NULL'";
$result = mysqli_query($conn, $query);
$i = 1;
while ($row = mysqli_fetch_array($result)) {
$sId = $row['student_id'];
$sName = $row['name'];
echo "<tr id='".$sId."'>";
echo "<td>".$i." - </td>";
echo "<td>$sId</td>";
echo "<td>$sName</td>";
echo "<td><button name='sAcc' id='acc-".$sId."' onclick='approveuser(this.id)'>Accept</button></td>";
echo "<td><button name='sRej' id='rec-".$sId."' onclick='approveuser(this.id)'>Reject</button></td>";
echo "</tr>";
$i++;
}
}
getStudent();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function approveuser(id){
trid=id.split('-')[1];
//alert(trid);
$.ajax({
url: "update.php",
type:"post",
data:{ val : id },
success: function(result){
//alert(result);
$('table#sHold tr#'+trid).remove();
alert('Updated');
}
});
}
</script>
//The code give below this update.php pge(ajax page)
<?php
$data=$_POST['val'];
$status =explode('-',$data);
$user_id=$status[1];
if($status[0]=='acc'){
$value=1;
}
elseif($status[0]=='rec'){
$value=0;
}
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
mysqli_query($conn,"update student_table set status='$value' where student_id=$user_id");
?>
I have the following code and it works great, I just want to convert it to live so it updates every 10 seconds or so without a page refresh, I'm guessing I'll need to use AJAX or Jquery but I lack the knowledge on how to do so.
=====VIA <?php include("database.php"); ?>====
<?php
// Create connection
$con=mysqli_connect("ip/host","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
====ON THE PAGE====
<? php
$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");
while ($row = mysqli_fetch_array($result)) {
echo "<div class='infobox_data'>Temperature: ".$row['TEMP']."°C</div>";
echo "<div class='infobox_data'>Humidity: ".$row['HUMID']."%</div>";
echo "<div class='infobox_time'>Captured: ".date("g:i:s a F j, Y ", strtotime($row["TIME"]))."</div>";
}
mysqli_close($con); ?>
Got it working, thanks for the help everyone.
Javascript
$(document).ready(function(){
loadstation();
});
function loadstation(){
$("#station_data").load("station.php");
setTimeout(loadstation, 2000);
}
station.php
<?php
include ("database.php");
$result = mysqli_query($con, "SELECT * FROM sql347511.1 ORDER BY ID DESC LIMIT 1;");
while ($row = mysqli_fetch_array($result))
{
echo "<div class='infobox_data' id='infobox_temp'>" . $row['TEMP'] . "°C</div>";
echo "<div class='infobox_data' id='infobox_humid'>" . $row['HUMID'] . "%</div>";
echo "<div class='infobox_time'>At " . date("g:i:s a F j, Y ", strtotime($row["TIME"])) . "</div>";
}
mysqli_close($con);
?>
Where to put the data
<div id="station_data"></div>
You can make inputs from div on double click and then get this inputs value through jquery:
$().val;
then using ajax send this value to php:
$.ajax({
url: 'url_to_php_which_update_mysql',
data: {'data': 'value_from_input'},
cache: false,
success: function(response){
$(input).val(response);
}
});
And in php file you need to upload $_GET['data'] in Database
I am making a dynamic web page that allows people to post their favorite recipes. Below each recipe is a link that allows you to make a comment on the recipe. If you make a comment, the comment will be posted in the database UNLESS the comment has any apostrophes in it. Here's the code for the addcomment.inc.php page:
<?php
$con = mysql_connect("localhost", "test", "test") or die('Sorry, could not connect to database server');
mysql_select_db("recipe", $con) or die('Sorry, could not connect to database');
$recipeid = $_GET['id'];
$query = "select title from recipes where recipeid = $recipeid";
$result = mysql_query($query) or die('Could not retrieve file: ' . mysql_error());
echo "<form action=\"index.php\" method=\"post\">\n";
if (mysql_num_rows($result) == 0) {
$title = "Unknown Title";
}
else {
while($row=mysql_fetch_array($result, MYSQL_ASSOC)) {
$title = $row['title'];
}
}
echo "<h2>Enter your comment for the recipe \"$title.\" </h2>";
echo "<textarea rows=\"10\" cols=\"50\" name=\"comment\"></textarea><br>\n";
echo "Submitted by:<input type=\"text\" name=\"poster\"><br>\n";
echo "<input type=\"hidden\" name=\"recipeid\" value=\"$recipeid\">\n";
echo "<input type=\"hidden\" name=\"content\" value=\"addcomment\">\n";
echo "<br><input type=\"submit\" value=\"Submit\">\n";
echo "</form>\n";
?>
A different php file called addcomment.inc.php retrieves the information. This is the code below:
<?php
$recipeid = $_POST['recipeid'];
$poster = $_POST['poster'];
$comment = htmlspecialchars($_POST['comment']);
$date = date("Y-m-d");
$con = mysql_connect("localhost", "test", "test") or die('Could not connect to server');
mysql_select_db("recipe", $con) or die('Could not connect to database');
$query = "INSERT INTO comments (recipeid, poster, date, comment) " .
" VALUES ($recipeid, '$poster', '$date', '$comment')";
$result = mysql_query($query) or die('Could not query databse. ' . mysql_error());
if ($result)
echo "<h2>Comment posted</h2>\n";
else
echo "<h2>Sorry, there was a problem posting your comment</h2>\n";
echo "Return to recipe\n";
?>
How can I make this code properly handle single quotes if inputted into a comment form?
Before you glue anything into the MySql query pass it through mysql_real_escape_string()
Before you glue anything into HTML pass it through htmlspecialchars()
This way you can prevent SQL injections, JavaScript/HTML injections and wildfires.
You have to use mysql_real_escape_string()
$comment = mysql_real_escape_string($_POST['comment']);
You have to escape the input when you pass it on to MySQL with mysql_real_escape_string(), to avoid that the user can perform an SQL injection and do stuff evil with your database.
Example:
// wrong
$query = "select title from recipes where recipeid = $recipeid";
// correct
$query = "select title from recipes where recipeid = " . mysql_real_escape_string($recipeid);
You also have to escape the output when you pass it on to the browser with htmlspecialchars() (or urlencode() in URLs), otherwise someone could insert some malicious HTML or JavaScript code in your database, and then attack your other users with a XSS attack.
Example:
// wrong
echo "<input type=\"hidden\" name=\"recipeid\" value=\"$recipeid\">\n";
echo "Return to recipe\n";
// correct
echo "<input type=\"hidden\" name=\"recipeid\" value=\"" . htmlspecialchars($recipeid) . "\">\n";
echo "Return to recipe\n";
actually i want to send a comment to the each image and it should display just after clicking the button . I am able to do insert and retrieve the comment but it require refresh the page and i don't want to refresh....just like orkut.plz help me i m new in php...
thans to all............
insertimg.php
//________________________________________FOR INSERT COMMENT_____________________________________________________
if (isset($_POST['Submit']))
{
$sql = "INSERT INTO comment(imid, comm) values ('".mysql_real_escape_string(stripslashes($_REQUEST['imgId']))."', '".mysql_real_escape_string(stripslashes($_REQUEST['Comment']))."')";
//$sql = "INSERT INTO comment (com) VALUES ($_POST['Comment'])";
//$sql="UPDATE upload SET comm='$_REQUEST['Comment']'WHERE id='$_REQUEST['imgId']'";
if($result = mysql_query($sql ,$conn))
{
echo "submited:";
}
else
{
echo "<h1>problem </h1> ".mysql_error();
}
}
For display comment..
$page=$_GET["page"];
$sql = "select comm from comment where imid = '".$page."'";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo"Comments:";
echo "<br>";
echo "<br>";
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo $row['comm'];
echo "<textarea name=\"Comment\" style=\"background-color:#81F7BE;\">"; echo $row['comm']; echo "</textarea>";
//echo "<font>";
echo "<br>";
echo "<br>";
}
mysql_close($conn);
?>
You can solve it with AJAX.
You can use something like jQuery Ajax library.
$.ajax({
type: "POST",
url: "inserting.php",
data: "imid=1&comm=Hi",
success: function(msg){
alert( "Ajax Response: " + msg );
}
});