I want to update a column in a table in mysql. Basically the column is the flag for the entries of that db table.
The modification of the column is resetting all values to 0 and setting the desired row to 1, for this reason I have post.php file which looks like
<?php
require_once('class.uuid.php');
$connection = mysql_connect("---logindetailshere---");
$db = mysql_select_db("---dbnamehere---",$connection);
switch($_REQUEST['action']){
case ...
break;
case ...
break;
case 'changeDisp':
changeDisp($_REQUEST['uid']);
break;
}
mysql_close($connection);
...
function changeDisp($uid){
global $connection, $db;
$q_string = "UPDATE Questions SET Displayed = 0";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
$q_string = "UPDATE Questions SET Displayed = 1 WHERE Uid='${uid}'";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
}
?>
on the webpage I display the items and radiobuttons next to the items, the purpose is to select the radiobuttons and post to set the flag 1 for the selected item, for this reason I have a item.php file
<?php
$i = 1;
foreach ($qitem as &$q) {
$options = explode(";", $q["Options"]);
$displayed = '';
if ($q["Displayed"] == 1) { $displayed='checked="yes"'; }
echo("<div class='item' name='".$q["iUid"]."'>");
echo("<div class='count'>".$i.".</div>");
echo ("<div class='radio'><input type='radio' onclick='changeDisp("".$q["Uid"]."")' name='disp' ".$displayed."></div>");
echo("<div class='left'>");
echo("<h4>".$q["Value"]."</h4>");
echo("<div class='details'>Typ: ".$q["Type"]."</div>");
echo("<div class='details'>Skala: ".$options[0]." / ".$options[1]."</div>");
echo("</div>");
echo("</div>");
$i++;
}
?>
here I am using radiobuttons to select the related item, I checked the unique id values using firebug the values are fine, I just want to click on any radiobutton and want to trigger the onclick=changeDisp() function.
I have no idea why the page doesn't reload itself and change the selected flag to 1. Could you please help me to solve this problem?
Thanks in advance.
You cannot use an onclick function to call php function without going there with a javascript, jQuery or ajax call. You could create an ajax script to call the post.php From the item.php page and return the results to you.
Here is an example of creating the function you want. This assumes that $uid is coming from a radio button and not an actual user input. If the user can directly input something you need to use a prepared statment
function changeDisp($uid)
{
$Mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($Mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $Mysqli->connect_errno . ") " . $Mysqli->connect_error;
$Mysqli->close();
}
$query = "UPDATE Questions SET Displayed = 1 WHERE Uid='".$uid."'";
$update = $Mysqli->query($query);
if($update)
{
return true;
}
return false;
}
Related
I wrote this code to comment system on my webpage. But i want to keep showing all data on web page while another people do comment and see another people's comment
include 'connection.php';
$con1= new connection();
$db=$con1-> open();
$qry= "INSERT INTO post (content) VALUES ('".$_POST["commentEntered"]."')";
$db->exec($qry);
if(isset($_POST['Submit'])) {
if ($con1->query($qry) === TRUE) {
echo "Your Comment Successfull Submited";
} else {
echo "Error: " . $qry . "<br>" . $con1->error;
}
$sql = 'SELECT * FROM post';
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$con1->close();
}
if ($_POST)
echo "<h2> Your Comment Successfully Submitted</h2> <br> ".$_POST['commentEntered']."<br>";
}
?>
after your select, inside your if($_POST) write this
while ($row = $q->fetch()) {
foreach($row as $key=>$val){
if (!is_numeric($key)) echo "<p>$key=>$val</p>";
}
}
EDIT i'm not 100% sure you can close the connection and still do a ->fetch, (I think you can but i've never tried it) so you may have to move your connection close after this (but I think you'll be alright), also I am not sure if setFetchMode will return duplicate numbered keys or not so as a precaution I have filtered for them you may not need to
So I am trying to make a discussion board and I have a table of posts being queried in one column of a table on the discussion board page. I then have the buttons of those post set up to a function onclick (where I am passing the post ID and then posting it to set_id.php to set as $_SESSION['name'] = $_REQUEST['name']):
scripts.js:
function getcomments(id){
$("#success_child").empty();
$.post("discussion_topics/set_id.php", {
"name": id}).done($("#success_child").load("discussion_topics/comments.php",
function(responseTxt, statusTxt, xhr){
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
}));
}
The problem is, although the Post ID is being set correctly, the php file being loaded will load the previously set SESSION variable that is the post ID. I have absolutely no idea why.
Basically, the SEssion variable is being set properly, however, when a new post is clicked, it will query in the comments.php the old session ID, then when you click again it will query that last one that didn't show. Basically a delay somehow. But it is not a time delay because I have tried that.
HELP!
comment.php:
<?php
session_start();
echo $_SESSION['name'];
function draw_table(){
/* draw table */
$table = '<table cellpadding="0" cellspacing="0" class="discuss_table">';
//Connect To Database
$hostname="localHost";
$username="removed";
$password="removed";
$dbname="removed";
$usertable="replys";
mysql_connect($hostname,$username, $password) or die ("<html> <script>alert('Unable to connect to database! Please try again later.'),history.go(-1)</script>");
mysql_select_db($dbname);
# Check If Record Exists
$id = $_SESSION['name'];
$query = "SELECT * FROM $usertable WHERE post_id = $id";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
//build table for post
$date = date("M d Y h:ia e", strtotime($row["date"]));
$table.="<tr>";
$table.= "<p class=\"discussion_title\">";
$table.= "<b>".$row["title"]."</b>"."<br>";
$table.=$row["name"].", ".$date." for topic ".$row["topic"]."<br>";
$table.=$row["content"]."<br>";
$table.="<button class=\"makecomment_buttons\">Reply</button>";
$table.="</p></tr>";
}
}
//end the table
$table.= '</table>';
//all done, return result
return $table;
}
echo draw_table();
echo "<br>";
?>
set_id.php
<?php
session_start();
$_SESSION['name'] = $_REQUEST['name'];
?>
Solution found, but new problem occured - displayed at bottom of this question
I have created this while loop which shows all content from my db and gives the user the possibility to edit it by entering a new value and pressing the 'Update' button. Everything works fine except that when I press the 'Update' button, the value of my object is erased in stead of updated. So the value of my input field becomes blank, but it has to display the value that was filled in.
I'm almost certain that the problem is within the last part my PDO code (in the function Update), but can't point my finger on it. Can you help me?
Connection to my PDO code
<?php
include_once('classes/Day.class.php');
$d = new Day();
$all = $d->getAll();
if(isset($_POST['update'])){
$d->Report = $_POST['myreport'];
$d->Id = $_POST['hidden'];
$d->Update();
}
?>
My while loop
<?php
while ($displayAll = $all->fetch(PDO::FETCH_ASSOC)) {
echo
"
<form method='POST' action=''>
<label>Day " . $displayAll['id'] . ":</label>
<input type='text' name='myreport' value='" . $displayAll['myreport'] . "' />
<input type='hidden' name='hidden' value='" . $displayAll['id'] . "' />
<button type='submit' name='update''>Update</button>
</form>
";
}
?>
My functions
<?php
include_once('Db.class.php'); // connection to the Db.
class Day{
private $m_iId;
private $m_sMyreport;
public function __set($p_sProperty, $p_vValue){
switch($p_sProperty){
case 'Id':
$this->m_iId = $p_vValue;
break;
case 'Myreport':
$this->m_sMyreport = $p_vValue;
break;
}
}
public function __get($p_sProperty){
switch($p_sProperty){
case 'Id':
return $this->m_iId;
break;
case 'Myreport':
return $this->m_sMyreport;
break;
}
}
public function Update(){
$conn = Db::getInstance();
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare("
UPDATE `tbl_dailyreport`
SET `myreport` = :myreport
WHERE `id` = :id
");
$statement->bindValue(":myreport",$this->m_sMyreport);
$statement->bindValue(":id",$this->m_iId);
$statement->execute();
}
public function getAll () {
$conn = Db::getInstance();
$result = $conn->query("SELECT * FROM tbl_dailyreport");
return $result;
}
}
?>
All help is appreciated!
Edit: solution found + new problem
$d->Report = $_POST['myreport'];
in "Connection to my PDO code" has to become
$d->Myreport = $_POST['myreport'];
because it has to be equal to the case items in the setter and getter. The annoying thing now is that when I press 'Update' the previous message is still visible, so I have to double refresh. Any solutions for this?
If I understand You correctly You will have to load current results just after the update:
if(isset($_POST['update'])){
$d->Report = $_POST['myreport'];
$d->Id = $_POST['hidden'];
$d->Update();
$all = $d->getAll();
}
This way, after the update You will have fresh (updated) results that You can display in My while loop.
I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.
I have a php which would check for certain value if it exists in a mysql database. If the value does not exists, it would simply add the value and refresh the page once to load the page again and now it has a value in the database, would go ahead to add other values. How do I refresh page just once when it is called ?
<?php
$sname = "W3 schools C# tutorials";//$_POST["sitename"];
$stype = "C#";//$_POST["sitetype"];
$saddy = "www.w3schools.com";//$_POST["siteaddress"];
$scomm = "W3 schools C# tutorials";//$_POST["sitecomment"];
$conn = mysql_connect("localhost","root","password");
if(!$conn){
die("Could not connect: ".mysql_error());
} else {
mysql_select_db("bookmarks",$conn);
$rs = mysql_query("select TypeId from bookmarktypes where TypeName = '$stype'");
$row = mysql_fetch_array($rs);
if($row > 0 ){
//Data found, continue to add...
} else {
//No data... insert a valid one
$rs = mysql_query("insert into bookmarktypes (TypeName) values ('$stype')");
if (!$rs){
die('Error: ' . mysql_error());
} else {
//echo "inserted new type data...";
}
//echo "</html>";
}
}
mysql_close($conn);
//Refresh page once
?>
There's the comment to refresh page below after mysql close command.
Refresh it right after insert with
header('Location: url here');
exit;
Btw, read a little about sql injections
Also - mysql_close() is pointless there.
if(check=1)
{
echo "\"<meta http-equiv=\"refresh\" content=\"2;url=http://yourwebsite.com/\">\"\n";
}
if you need to print the data that you just have entered try this
header('Location: YourShowDataPage.php?id='.$_POST['id_dataEntered'])
mi apologizes if is wrong , im a begginer