This is weirding me out quite a bit...
If i delete the update statement it dont update the "views" at all... which makes sence.
If i delete the "Delete html" and run the file it will update once and not twice as it should? which does not make sense at all
How is this even possible, especially when there only are one update query and when it is plain HTML that needs to be deleted?
If anyone is interested i am prepared to do teamviewer if you do not belive me.
This is the sample page
All of the code seperated in blocks for readability
$stmt = $dbCon->prepare("SELECT id, views, rating, votes FROM rating ORDER BY id DESC LIMIT 1");
$stmt->execute();
$stmt->bind_result($id, $views, $rating, $votes);
$stmt->fetch();
$stmt->close();
$average = averageRate($rating, $votes);
$string1;
$string1 .= "<p>Id = " . $id . "</p><br>";
$string1 .= "<p>Views = " . $views . "</p><br>";
$string1 .= "<p>Rating = " . $rating . "</p><br>";
$string1 .= "<p>Votes = " . $votes . "</p><br>";
$string1 .= "<p>Average = " . averageRate($rating, $votes) . "</p><br><br>";
The update query
//THIS IS THE UPDATE QUERY PROBLEM
//UPDATERE DATABASED
$stmt = $dbCon->prepare("UPDATE rating SET
views = views + 1 WHERE id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
Delete HTML (If i delete this HTML the SQL updates once, weird right? the JS is whats used with that HTML)
<div class="topNav">
<span class="topNavArrow">
</span>
<div class="categoryWrapper">
<div id="categoryParent">
<input id="category01" class="categorys" type="checkbox" value="1" checked>
<input id="category02" class="categorys" type="checkbox" value="2" checked>
<input id="category03" class="categorys" type="checkbox" value="3" checked>
</div>
<label for="category01">
<img src="#" alt="category 01">
</label>
<label for="category02">
<img src="#" alt="category 02">
</label>
<label for="category03">
<img src="#" alt="category 03">
</label>
</div>
</div>
<script>
document.querySelector("#categoryParent").addEventListener("click", checkedCategory, false);
var categorys = document.getElementsByClassName("categorys");
var categorysLength = categorys.length;
var checked = "1,2,3";
function checkedCategory(e) {
checked = "";
for (var c = 0; c < categorysLength; c++) {
if (checked) {
var separator = ",";
} else {
var separator = "";
}
if (categorys[c].checked) {
checked += separator + categorys[c].value;
}
}
alert(checked);
e.stopPropagation();
}
</script>
The rest of the HTML
<div id="contentWrapper" class="contentWrapper">
<?php echo $string1;?>
<div class="contentInner">
<div class="contentHelper">
<div class="contentInfo">
<p id="contentViews">Views: <?php echo $views; ?></p>
<p>Votes: <?php echo $votes; ?> </p>
<p>Average: <?php echo $average; ?>/5</p>
<p class="<?php echo $voteYesNo; ?>"><?php echo $voteText ?></p>
</div>
<div class="contentImg">
</div>
</div>
</div>
</div>
Searched STO but i could not find any questions that covered my problem but some similair like this link
And no this is not a bad joke it is really whats going on...
Related
I am coding a website for an online university portal where I have a programs/courses page in which I am displaying the programs/courses on the page using data from the database in a PHP while-loop I have the enroll buttons also being displayed in that same while loop. but I'm having a bit of difficulty submitting the enroll buttons as when I click one of them all of them get submitted.
can anyone please let me know what I'm doing wrong here or if I have to use any javascript in this case!
<?php
session_start();
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'htdatabase');
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$id = $_SESSION['userID'];
$sql = "SELECT * FROM programs";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$i = '';
$progID = $row["progID"];
$name = $row["progName"];
$halfTime = $row["halfTDuration"];
$fullTime = $row["fullTDuration"];
$fee = $row["fee"];
$descrip = $row["description"];
$stringname = strval($name);
$spaceRemoved = str_replace(' ', '', $stringname);
?>
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<?php echo "<button class='btn btn-link' type='button' data-toggle='collapse' data-target='#$spaceRemoved' aria-expanded='false' aria-controls='$spaceRemoved'> $name </button>"; ?>
</h5>
</div>
<?php echo "<div id='$spaceRemoved' class='collapse' aria-labelledby='headingOne' data-parent='#accordionExample'>"; ?>
<div>
<div class="ccard-body col-md-9">
<h6><?php echo $descrip; ?></h6>
<hr>
<h5>Duration:</h5>
<h6>Full time: <?php echo $fullTime; ?></h6>
<h6>Half time: <?php echo $halfTime; echo $i; ?></h6>
<hr>
<h5 style="display: inline-block;">Estimated fees: $</h5><h5 style="display: inline-block;"><?php echo $fee ?></h5>
</div>
<form action="programs.php" method="post">
<div id="enroll" class="col-md-3">
<?php
$sql1 = "SELECT * FROM userprograms WHERE userID = '$id' AND progID = '$progID'";
$result1 = $con->query($sql1);
if ($result1->num_rows > 0) {
echo '<div id="enrolled" name="enrolled">ENROLLED</div>';
} else {
if (isset($_POST["enroll"])) {
$enrollqry = "insert into userprograms (userID, progID) values ('$id' , '$progID')";
mysqli_query($con, $enrollqry);
}
echo "<button name='enroll'type='submit'>ENROLL</button>";
}
?>
</div>
</form>
</div>
</div>
<?php
}
} ?>
You can specify a value for the button. like
<button name='enroll' value="<?php echo $program_id?>" type='submit'>ENROLL</button>
Then when checking for $_POST['enroll'] check the value and also validate it before entry to db.
After clicking the submit button a browser will send a POST request to programs.php with a form data, that includes values of input & button tags.
<input type="submit" name="course1" value="42">Subscribe</input>
<input type="text" name="first_name" placeholder="Your name"/>
Will send
course1=42
first_name=...
So you should either give a unique name to each submit button to be able to distinguish them on the server-side, or set up distinct values, as #mohamed-jailam mentioned above.
i want to add commenting to each article, so inside my"foreach"cycle I added commenting to each article, but "set a comment" function runs to all art
thats the code for making an article window
<?php $articles_qr = mysqli_query($connection, "SELECT * FROM `articles` ");
$articles = array();
while ( $art = mysqli_fetch_assoc($articles_qr))
{
$articles[] = $art;
}
?>
<?php foreach ($articles as $art)
{
?>
<section>
<div class="containerstuff">
<div class="stuffpic">
<img src="<?php echo "../static/imagespages/",$art['image'] ?>" class="pico">
</div>
<div class="article">
<h1><?php
echo $art['title']
?>
</h1>
<?php
echo $art['text'];
echo $art['id']
?>
</div>
</div>
<div class="scrollmenu">
<?php include "../includes/comments.php";?>
</section>
<?php
} ?>
thats the code comments window
<?php
date_default_timezone_set(timezone_identifier);
include_once '../comments.ink.php'
?>
<div class="containercom">
<img src="#" class="commpic">
<p class="comment"></p>
</div>
<div class="blockcom">
<form class='form' method='POST' action="<?php echo setComments($connection)?>">
<div class='form__group'>
<input type='hidden' name='page_id' value="<?php echo $art['id']?>" >
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='pubdate' value="<?php echo date('Y-m-d H:i:s')?>" >
<textarea name='text' class='form__control' placeholder ='Введите комментарий...' required=''></textarea>
</div>
<div class='form__group'>
<input type='submit' class='form__control2' name='commentSubmit'></input>
</div>
</div>
</form>
and thats the code for INSERT function
<?php
static $firstTime = true;
function setComments($connection) {
if(isset($_POST['commentSubmit'])){
$idcom = $_POST['page_id'];
$uid = $_POST['uid'];
$pubdate = $_POST['pubdate'];
$text = $_POST['text'];
$sql =
"INSERT INTO `comments` (page_id, uid, pubdate, text)
VALUES ('$idcom', '$uid', '$pubdate', '$text')";
$result = $connection->query($sql);
$firstTime = false;
}
}
so how can i make insert only for 1 article (so when i add it now, there are appears as many comments as many articles i have in database)
I think you should use ajax to append a new comment which is the widely used solution, the way u r doing will become difficult to handle for you.
I haven't found the solution, so I just selected another way.
For each article I placed a button to post a comment which will send user to the page with this article and for this button for "href" I wrote php code (href = "comments.php?id=<?php echo $art['id']"?>) and for this page I use $_GET to select articles only for this id. Then I just placed there comments-function that I wrote so it works alright now because function works only for 1 argument
i have this Interface where the user can add a flower
The user need to add a flower to the database and he can make them in different occasions a categories (the check boxes). Now to implode the data i made this code:
$occasions = implode( ';' , $_POST['reg_occassions'] );
$categories= implode( ';' , $_POST['reg_categories'] );
$query =
"INSERT INTO tbl_flower (flower_type, website_description,florist_description,name,image,enabled,florist_choice,categories,occasions)
VALUES ('$flowertype', '$websitedescription', '$floristdescription','$name', '$upfile', '$enabled','$floristchoice', '$categories','$occasions')";
In the database they save as follows :
id flower name occasions categories
1 Rose Birthday;Valentines Bouqet;flower arrangment
Now the user can edit a flower too.This is the interface
PROBLEM!:
i dont have an idea how can i make the checkboxes again and show him which one he checked and he can change the data. I need to know how can i show the checkboxes and which one he checked will be checked too .
Thank and I really appreaciate if someone can help me.
EDIT Answer: This is the interface of the checkboxes.
You can do something like:
$results = "Bouqet,flower arrangment"; //results from your database
$resultsArray = explode(",", $results); //split the comma
$checkValue = array("Bouqet", "flower arrangment", "other"); //your checkbox values
$html = "";
foreach($checkValue as $val)
{
if(in_array($val,$resultsArray ))
$html .= '<input type="checkbox" name="flower" value="'.$val.'" checked>'.$val.'<br>';
else
$html .= '<input type="checkbox" name="flower" value="'.$val.'">'.$val.'<br>';
}
echo $html;
Check Demo Here
EDIT: I am making this edit because of your comments, you need to do something like:(not tested)
<div class="table-responsive col-md-4">
<table>
<thead>Occasions</thead>
/**flower occassions **/
$flowerCategoriesQry "SELECT categories FROM tbl_flower where id = 1"; //you need to change the where clause to variable
$flowerResults = mysqli_query($conn, $flowerCategoriesQry)
$categoriesRow = $flowerResults->fetch_assoc();
$resultsArray = explode(",", $categoriesRow['categories']);
/**All Occassions **/
$query544="SELECT name FROM tbl_occasions";
$results544 = mysqli_query($conn, $query544);
while ($row = $results544->fetch_assoc()) { ?>
<div class="col-md-12">
<label class="checkbox" for="checkboxes">
<?php
if(in_array($row['name'],$resultsArray ))
{
?>
<input type="checkbox" name="flower" value="<?php echo $row['name'];?>" checked> <?php echo $row['name'];?> >
<?php }
else{
?>
<input type="checkbox" name="flower" value="<?php echo $row['name'];?>" ><?php echo $row['name'];?> >
<?php echo} $row['name']?> </label>
</div> <?php }?>
</table>
This is the answer. Thanks to the Flash!
session_start();
$conn = ConnectToSql();
?>
<div class="table-responsive col-md-6" style="border:1px solid blue">
<div class="col-md-6">Categories</div>
<div class="col-md-6">Occasions</div>
<hr>
<div class="col-md-6">
<?php
/**flower occassions **/
$flowerCategoriesQry= "SELECT categories FROM tbl_flower where id ='$_SESSION[flower]'";
$flowerResults = mysqli_query($conn, $flowerCategoriesQry) ;
$categoriesRow = $flowerResults->fetch_assoc();
$resultsArray = explode(";", $categoriesRow['categories']);
/**All Occassions **/
$query544="SELECT name FROM tbl_categories";
$results544 = mysqli_query($conn, $query544);
while ($row = $results544->fetch_assoc()) { ?>
<label class="checkbox" for="checkboxes">
<?php
if(in_array($row['name'],$resultsArray ))
{
?>
<input type="checkbox" name="edit_categories[]" value="<?php echo $row['name'];?>" checked> <?php echo $row['name'];?>
<?php
}
else{
?>
<input type="checkbox" name="edit_categories[]" value="<?php echo $row['name'];?>" ><?php echo $row['name']; } ?>
</label>
<?php
}
?>
</div>
click here for code
I'm in need of a bit help. I'm trying to find out how to associate a specific query (deletion of a record) with not the id of a record, but the record with which another query (selection of a record) is echoed out.
This line of code totally works when the id is specified, but again I need it for the record that gets called, where the id can skip numbers if I delete a record.
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
I've got a table in my phpmyadmin database with columns 'id', 'pagetitle', 'toevoeging' (addition in Dutch) , 'message'. First one is an INT, rest are varchars/text.
This may be a stupid question, I'm sorry for that. I'm still new to PHP, and to programming in general.
Here is the code. I've commented on lines code to clarify. Thanks you!.
<?php
if (isset($_SESSION['email'])) //if the admin is active, forms can be written out.
{
echo '</nav>
<br><br> <div class="inlogscript">
<form action="verstuurd.php" method="post">
<input type="text" placeholder="Titel" method="POST" name="pagetitle" /><br><br>
<input type="text" placeholder="Toevoeging" method="POST" name="toevoeging" /><br><br>
<textarea class="pure-input-1-2" placeholder="Wat is er nieuws?" name="message"></textarea><br>
<input type="submit" value="Bevestigen" />
</form></div>';
}
?>
<div class="mainContent">
<?php
include_once("config.php"); //this is the database connection
$query = "SELECT * FROM paginas "; //selects from the table called paginas
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
$pagetitle = $row['pagetitle'];
$toevoeging = $row['toevoeging'];
$message = $row['message'];
echo '<article class="topcontent">' . '<div class="mct">' . '<h2>' . "$pagetitle" .'</h2>' . '</div>' . "<br>" .
'<p class="post-info">'. "$toevoeging" . '</p>' . '<p class="post-text">' . '<br>'. "$message" . '</p>' .'</article>' . '<div class="deleteknop">' . '<form method="post">
<input name="delete" type="submit" value="Delete Now!">
</form>' . '</div>' ;
} //This long echo will call variables $pagetitle, $toevoeging and &message along with divs so they automatically CSS styled,
//along with a Delete button per echo that has the 3 variables
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
if (isset($_POST['delete'])) //Deletes the query if 'delete' button is clicked
{
$resulttwo = $mysqli->query($querytwo);
}
?>
</div>
</div>
Also here is the Insert INTO query of the records. Thanks again!
$sql = "INSERT INTO paginas (pagetitle,toevoeging, message)
VALUES ('$_POST[pagetitle]','$_POST[toevoeging]','$_POST[message]')";
//the insertion into the table of the database
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: ". $sql . "" . $MySQLi_CON->error;
}
This won't be sufficient but, to begin with your echo :
echo '<article class="topcontent">
<div class="mct">
<h2>' . $pagetitle .'</h2>
</div><br>
<p class="post-info">'. $toevoeging . '</p>
<p class="post-text"><br>'.$message.'</p>
</article>
<div class="deleteknop">
<form method="post">';
// you ll want to use $_POST["id"] array to delete :
echo '<input type="hidden" name="id" value="'.$row['id'].'">
<input name="delete" type="submit" value="Delete Now!">
</form>
</div>' ;
I create a spot on my clients website for them to post job openings for there business. I want to give them the option to edit the job post if they make a mistake after they post.
My question is how can I achieve this. Or better yet how can I pull up the info from my database so I can edit / save it?
This is what I have tried:
To get things started here is a screenshot of my database.
phpMyAdmin Database The table is called "hire" without the quotes.
I'm using 3 files/pages to try and get this to update.
The first is called modify-employment.php
<?php
$title = 'Modify Employment Opportunities';
$page_description = "We offer a complete dock service, rip rap installations, barge service, and custom built breakwaters.";
$thisPage="employment";
include_once($_SERVER['DOCUMENT_ROOT']."/admin/adminheader.php");
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
/* be safe, not sorry */
foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = mysql_real_escape_string($v);
}
/* take cat from url if exists */
$category = #$_REQUEST["category"] ? $_REQUEST["category"] : null;
$images = mysql_query(
$category ?
sprintf(
"SELECT * FROM hire WHERE data_type = '%s'",
$category
) :
"SELECT * FROM hire"
);
if ($images) {
$total = mysql_num_rows($images);
if ($total) {
$per = 4;
$page = #$_REQUEST["page"] ? $_REQUEST["page"] : 1;
$pages = ceil($total/$per);
}
mysql_free_result($images);
}
?>
misc code...
<section class="grid_8">
<ul class="clearfix">
<?php
if ($category) {
$images = mysql_query(sprintf(
"SELECT * FROM hire WHERE data_type = '%s' ORDER BY id DESC LIMIT %d, %d",
$category, ($page - 1) * $per, $per
));
} else $images = mysql_query(sprintf(
"SELECT * FROM hire ORDER BY id DESC LIMIT %d, %d",
($page - 1) * $per, $per
));
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>">
<article class="box white-bg">
<h2 class="red3-tx"><?=$image["title"] ?> <span class="date-posted blue2-tx"><?=$image["date"] ?></span></h2>
<div class="dotline"></div>
<p class="blue3-tx"><?=$image["description"] ?><br />
<br />
For more information please call ###-###-####.</p>
<h4 class="btn-green">Delete</h4>
<h4 class="btn-green">Update</h4>
</article>
</li>
<?php
}
?>
Here is a screenshot of what the above looks like:
So by using this line of code:
<h4 class="btn-green">Update</h4>
I click the update button and it locates the posts id number.
By clicking the update button it takes me to file #2 "update-emploment.php"
I want this page to bring in the data from the original job post so I can edit and save the info.
This is where I'm getting lost.
Here is my code for update-employment.php
<?php
$title = 'Admin Employment Opportunities';
$page_description = "Add description in here.";
$thisPage="employment";
include_once($_SERVER['DOCUMENT_ROOT']."/admin/adminheader.php");
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
/* be safe, not sorry */
foreach ($_REQUEST as $k => $v) {
$_REQUEST[$k] = mysql_real_escape_string($v);
}
/* take cat from url if exists */
$category = #$_REQUEST["category"] ? $_REQUEST["category"] : null;
$images = mysql_query(
$category ?
sprintf(
"SELECT * FROM hire WHERE data_type = '%s'",
$category
) :
"SELECT * FROM hire"
);
if ($images) {
$total = mysql_num_rows($images);
if ($total) {
$per = 4;
$page = #$_REQUEST["page"] ? $_REQUEST["page"] : 1;
$pages = ceil($total/$per);
}
mysql_free_result($images);
}
?>
misc code....
<form method="post" action="update-hire.php">
<input type="hidden" name="ud_id" style="width: 100%" value="<? echo "$id"; ?>" />
<div class="grid_6 botspacer60 ">
Position Title: <input type="text" name="ud_title" value="<?php echo "$title"; ?>"/>
<br /><br />
Date Posted: <input type="text" name="ud_date" value="<? echo "$date"; ?>"/>
<br /><br />
Position Details:<br />
<textarea name="ud_description" rows="8"><?php echo str_replace("<br />",chr(13),$des); ?><? echo "$description"; ?></textarea>
</div>
<div class="grid_12">
<input type="submit" value="Update" class="button orange" /> <div class="float-right"><input type="button" name="Cancel" value="Cancel" class="button orange" onclick="window.location = '/admin' " /></div>
</div></form>
The only part of the job post that gets echoed in is the title, not the title in my database, but the title of the page. See Image:
Then for the forms action I use file #3:
action="update-hire.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$ud_id = $_POST['ud_id'];
$ud_date = $_POST['ud_date'];
$ud_title = $_POST['ud_title'];
$ud_description = $_POST['ud_description'];
$ud_description = nl2br(htmlspecialchars($_POST['description']));
// Insert record into database by executing the following query:
$query="UPDATE hire SET title='$ud_title', description='$ud_description', date='$ud_date' "."WHERE id='$ud_id'";
$retval = mysql_query($sql);
echo "The position has been updated.<br />
<a href='modify-employment.php'>Update another position.</a><br />";
mysql_close();
?>
I'm very new to php and trying to learn on my own, but I spent a day trying to get this to work so I thought I would see If someone one Stack could help me out, as I've found some kind helpful people on here in the past. If someone could help I would appreciate it. Thanks!
In your update-employment.php, you need to define your variables. Add this somewhere in the file
$date = "";
$post_title = "";
$description = "";
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM hire WHERE id=".$id."");
while($row = mysql_fetch_assoc($result)) {
$date = $row->date;
$post_title = $row->title;
$description = $row->description;
}
And then change this line to be like so:
Position Title: <input type="text" name="ud_title" value="<?php echo "$post_title"; ?>"/>
When visiting the page, add ?id=1 to select a post id. Replace 1 with any desired id.
I cannot take credit for this as a friend helped me figure this out, but I didn't want to leave this question unanswered. Hopefully it could help someone else out there.
My 1st file modify-employment.php
This was fine.
2nd file update-emploment.php needed some work.
I commented out the original code and removed much code from the top of the file.
<?php
$title = 'Admin Employment Opportunities';
$page_description = "Add description in here.";
$thisPage="employment";
include_once($_SERVER['DOCUMENT_ROOT']."/admin/adminheader.php");
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
?>
Notice there was much code removed here.
misc code....
<div class="row">
<?php
$date = "";
$post_title = "";
$description = "";
$id = $_GET['value'];
/* $query = "SELECT * FROM hire WHERE id='$id'"; */
/* $result = mysql_query("SELECT * FROM hire WHERE id=".$id.""); */
$result = mysql_query("SELECT * FROM hire WHERE id='$id'");
$date = mysql_result($result,$i,"date");
$post_title = mysql_result($result,$i,"title");
$description = mysql_result($result,$i,"description");
/* while($row = mysql_fetch_assoc($result)) {
$date = $row->date;
$post_title = $row->title;
$description = $row->description;
} */
?>
<form method="post" action="update-hire.php">
<input type="hidden" name="ud_id" style="width: 100%" value="<? echo "$id"; ?>" />
<div class="grid_6 botspacer60 ">
Position Title: <input type="text" name="ud_title" value="<?php echo "$post_title"; ?>"/>
<br /><br />
Date Posted: <input type="text" name="ud_date" value="<? echo "$date"; ?>"/>
<br /><br />
Position Details:<br />
<textarea name="ud_description" rows="8"><?php echo str_replace("<br />",chr(13),$des); ?><? echo "$description"; ?></textarea>
</div>
<div class="grid_12">
<input type="submit" value="Update" class="button orange" /> <div class="float-right"><input type="button" name="Cancel" value="Cancel" class="button orange" onclick="window.location = '/admin' " /></div>
</div></form>
3rd file, action file: update-hire.php
I commented out the original code.
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$ud_id = $_POST['ud_id'];
$ud_date = $_POST['ud_date'];
$ud_title = $_POST['ud_title'];
$ud_description = $_POST['ud_description'];
/* $ud_description = nl2br(htmlspecialchars($_POST['description'])); */
// Insert record into database by executing the following query:
$query="UPDATE hire SET title='$ud_title', description='$ud_description', date='$ud_date' "."WHERE id='$ud_id'";
mysql_query($query);
/* $retval = mysql_query($sql); */
echo "The position has been updated.<br />
<a href='modify-employment.php'>Update another position.</a><br />";
mysql_close();
?>
That's it. Works like I wanted.