I have two form action buttons used in one of my php pages. When I click on first button, the second one is automatically loading. I am not PHP developer, so I do not know how to make button work separately. My form action button is like below:
//first button
<?php
echo
"<form action='' method='post'>
<input type='submit' class='btn btn-default' name='use_button' value='Remove Scores' />
</form>";
if(isset($_POST['use_button']))
{
$con=mysqli_connect('localhost', 'mydbuser', 'mydbpass', 'mydb');
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "TRUNCATE TABLE contest_score";
mysqli_query($con, $sql);
mysqli_close($con);
{
echo "Score Cleared";
}
}
?>
<br>
// second button
<?php
echo
"<form action='' method='post'>
<input type='submit' class='btn btn-default' name='use_button' value='Load Questions' />
</form>";
if(isset($_POST['use_button']))
{
$webcon = mysqli_connect('localhost', 'mydbuser', 'mydbpass', 'mydb');
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Queries for reading
*/
$questions = mysqli_query($webcon, 'SELECT * FROM `questions` ORDER BY RAND() LIMIT 30');
$mobcon = mysqli_connectmysqli_connect('localhost', 'mydbuser', 'mydbpass', 'mydb');
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
// remove old questions
$delete = "TRUNCATE TABLE questions";
mysqli_query($mobcon, $delete);
/**
* Insert data from old database
*/
// questions
while ($row = mysqli_fetch_array($questions))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `questions` (`option1`, `option2`, `option3`, `option4`, `correctans`, `question_text`, `cat_id`, `sub_cat_id`, `level_id`, `quesimage`) VALUES ('" . $row['option1'] . "', '" . $row['option2'] . "', '" . $row['option3'] . "','" . $row['option4'] . "','" . $row['correctans'] . "','" . $row['question_text'] . "','" . $row['cat_id'] . "','" . $row['sub_cat_id'] . "','" . $row['level_id'] . "','" . $row['quesimage'] . "');");
}
/*
Close Connections
*/
mysqli_close($mobcon);
mysqli_close($webcon);
{
echo "<script>alert('Questions Loaded');</script>";
}
}
?>
Can anyone suggest me to solve this issue?
Thanks.
I think the problem may be because you are using the same input name for the two buttons.
Try to change the second one to another name like:
<?php
echo
"<form action='' method='post'>
<input type='submit' class='btn btn-default' name='second_use_button' value='Load Questions' />
</form>";
if(isset($_POST['second_use_button']))
{
Related
I try to do a web page that contains a dropdown.
When dropdown is selected, I want to update the mark into MySQL database based on Enum, but the code does not work.
I use javascript with PHP to query into MySQL.
<form id="myForm" method="post" onsubmit="return submitform()">
<select id="lvl" name="lvl" style="height:30px;">
<option value="std1"selected="selected">
<?php echo $stu1name["Stu_name"] ?>
</option>
<option value="std2" >
<?php echo $stu2name["Stu_name"] ?>
</option>
<option value="std3" >
<?php echo $stu3name["Stu_name"] ?>
</option>
<option value="std4" >
<?php echo $stu4name["Stu_name"] ?>
</option>
<option value="std5" >
<?php echo $stu5name["Stu_name"] ?>
</option>
</select>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
This is my javascript with PHP:
function submitform() {
var option= document.getElementById('lvl').value;
if (option == "std1"){
?php
mysqli_query($conn,
"UPDATE evaluation set mid_mark='" . $_POST["mid_mark"] .
"',end_mark='" . $_POST["end_mark"] .
"', performance='" . $_POST["performance"] .
"' WHERE Enum ='1'"
);
?>
return true;
}
if (option == "std2"){
<?php
mysqli_query($conn,
"UPDATE evaluation set mid_mark='" . $_POST["mid_mark"] .
"',end_mark='" . $_POST["end_mark"] .
"', performance='" . $_POST["performance"] .
"' WHERE Enum ='2'"
);
?>
return true;
}
if (option == "std3"){
<?php
mysqli_query($conn,
"UPDATE evaluation set mid_mark='" . $_POST["mid_mark"] .
"',end_mark='" . $_POST["end_mark"] .
"', performance='" . $_POST["performance"] .
"' WHERE Enum ='3'"
);
?>
return true;
}
if (option == "std4"){
<?php
mysqli_query($conn,
"UPDATE evaluation set mid_mark='" . $_POST["mid_mark"] .
"',end_mark='" . $_POST["end_mark"] .
"', performance='" . $_POST["performance"] .
"' WHERE Enum ='4'"
);
?>
return true;
}
if (option == "std5"){
<?php
mysqli_query($conn,
"UPDATE evaluation set mid_mark='" . $_POST["mid_mark"] .
"',end_mark='" . $_POST["end_mark"] .
"', performance='" . $_POST["performance"] .
"' WHERE Enum ='5'"
);
?>
return true;
}
}
but when I update, all the row is updated like this
image
I don't know where I'm doing wrong here. I'm completely lost here.
This is because php run in the server and all code run before your page is loading, so you can't control it by script in the browser like javascript. You can insert data in tour database without javascript with this php code put at the top of your page. You have to delete the onsubmit statement in your form.
<?php
if (isset($_POST['lvl'])) {
$enum = substr($_POST['lvl'], -1, 1);
$sql = "UPDATE evaluation SET mid_mark=:mid_mark, end_mark=:end_mark, performance=:performance WHERE Enum='$enum'";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':mid_mark', $_POST['mid_mark'], PDO::PARAM_STR);
$stmt->bindParam(':end_mark', $_POST['end_mark'], PDO::PARAM_STR);
$stmt->bindParam(':performance', $_POST['performance'], PDO::PARAM_STR);
$stmt->execute();
}
?>
I am creating a forum where users are able to like and unlike posts and comments. The challenge I'm facing is that I would like the text of the like button to change without reloading the page. How can I go about differentiating between the buttons on the page and change individual button-texts from "Like" to "Liked" and vice versa? The buttons are, at the moment created and show like this:
<?php
$result3=mysqli_query($link, "SELECT * FROM cs_comments WHERE post_id = $postID");
while($row3 = mysqli_fetch_assoc($result3)){
$commentID=$row3['comment_id'];
$memberID=$row3['member_id'];
$likes=$row3['likes'];
$content= $row3['content'];
$anonymous=$row3['anonymous'];
if($anonymous=='1')
$name='Anonym';
else{
$result4= mysqli_query($link, "SELECT firstname, lastname FROM cs_members WHERE member_id = $memberID");
$row4=mysqli_fetch_assoc($result4);
$name = '' . $row4['firstname'] . " " . $row4['lastname'] . '';
}
$result5=mysqli_query($link,"SELECT * FROM cs_likes WHERE comment_id=$commentID AND member_id={$_SESSION['memberID']}");
if(mysqli_num_rows($result5)!=0)
$liked="unlike";
else
$liked="like";
echo '<div class="post_container">';
echo ' <div class="info_header">';
echo ' <div class="info_name">' . $name . '</div>';
echo ' <div class="info_group"></div>';
echo ' </div>';
echo ' <div class="post_content">';
echo $content;
echo ' </div>';
echo ' <div class="post_footer">';
echo ' <div class="like_button"><button onclick="likeComment('. $commentID . ')">' . $liked . '(' . $likes . ')</button></div>';
echo ' </div>';
echo '</div>';
}
mysqli_close($link);
?>
Javascript for onclick-event:
function likeComment(id) {
$.ajax({
url: '/resources/phpScript/like.php',
type: 'POST',
data: {comment_id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
Like.php
<?php
session_start();
include "./db-connect.php";
$memberID= $_SESSION['memberID'];
if(isset($_POST['post_id'])){
$postID=mysqli_real_escape_string($link,$_POST['post_id']);
$sqlCheck="SELECT * from cs_likes WHERE post_id = $postID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (post_id, member_id) VALUES ('$postID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE post_id= $postID AND member_id = $memberID";
}
elseif(isset($_POST['comment_id'])){
$commentID=mysqli_real_escape_string($link,$_POST['comment_id']);
$sqlCheck="SELECT * from cs_likes WHERE comment_id = $commentID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (comment_id, member_id) VALUES ('$commentID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE comment_id= $commentID AND member_id = $memberID";
}
else
echo "Something went wrong";
$checkResult=mysqli_query($link, $sqlCheck);
if(mysqli_num_rows($checkResult)==0)
$result=mysqli_query($link,$sqlInsert);
else
$result=mysqli_query($link,$sqlDelete);
?>
Any help is appreciated!
So I found the solution! I have little to no experience with javascript, which is why this may have been too simple of a question for anyone to find out what I was after!
This is what I did:
I simply sent the element clicked by adding this to the function call on click:
echo ' <div class="like_button"><button onclick="likePost('. $postID . ',this)">' . $liked . '</button></div>';
I then added this tiny bit to my function:
function likePost(id, elem) {
if(elem.innerHTML== "like")
elem.innerHTML="unlike";
else
elem.innerHTML="like";
I still want to thank everyone who made and effort to try understanding what I was asking.
i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter
Right now I have a grid and each grid part/bit contains an image, the name of the item and different buttons that can delete the item from the mysql database and update the price. What I want to do know is that when a user say clicks on the image a window would pop up where extra information would be displayed. However it is not a pop up in a usual sense that it would create another window but rather a pop up within the current window/tab. E.g. When you press on a photo in Facebook it creates almost like a popup on which you can comment or change to the next photo. Does anyone have any idea on how to do this or at least what is the whole thing/process called?
Sorry if I can't give a proper name but I don't know it myself :/
Here is the code to what I have now. I would prefer an actual code solution but if you can lead me to where I should look for it I would also be happy. I tried looking online however everything I get is window pop ups.
<div class="boxes">
<?php
$ID = $_SESSION['SESS_MEMBER_ID'];
$con = mysql_connect("", "", "");
if (!$con){
die("Cannot connect: " . mysql_error());
}
mysql_select_db("test", $con);
$sql = "SELECT * FROM items WHERE member_id = $ID";
$myData = mysql_query($sql, $con);
$dir = 'Images';
$symbol = '\\';
$end = 'r.jpg';
$currency = '£';
while($record = mysql_fetch_array($myData)) {
$real_name = str_replace('_', ' ', $record['Name']);
$result = $dir . $symbol . $record['Name'] . $end;
$value = $currency . $record['price_now'];
$link = $record['url'];
echo "<div class = frame>";
echo "<div class = bit-3>";
echo "<div class = box>" . "<img src=" . $result . " alt=some_text>";
echo "<br />";
echo "<br />";
echo $real_name;
echo "<br />";
echo "<br />";
echo "Price now: " . $value;
echo "<form action = member-profile-page.php method = post>";
echo "Desired price: ";
echo "<td>" . "<input type = text name = desired_price value = " . $record['desired_price'] . " </td>";
echo "<td>" . "<input type = hidden name = hidden value = " . $record['Id'] . " </td>";
echo " ";
echo "<td>" . "<input type = submit name = update value = Update" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = delete value = Delete" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = buy value = Buy" . " </td>";
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
if (isset($_POST['buy'])){
$query = "select url from items where Id = '$_POST[hidden]'";
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
$code = $row['url'];
echo "$code";
header("Location: $code");
}
};
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE items SET desired_price = '$_POST[desired_price]' WHERE Id = '$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM items WHERE Id = '$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
mysql_close($con);
?>
</div>
Sounds like you're looking for an overlay:
http://jquerytools.org/demos/overlay/index.html
or a modal:
https://jqueryui.com/dialog/
These are by no means the only examples; there are hundreds of such solutions. These will get you started, though. Good luck!
What you think about is just a layer in the current browser viewport, having some controls to let the user handle it like a "desktop window".
There are quite a lot of JS frameworks offering handy solutions for this, i.e. jQuery UI. Within there, look for "dialog"
I'm trying to insert a form in php statement like this
while($row = mysql_fetch_array($result))
{
echo "<form id='send' action='up.php' method='POST'>
<tr>
<td>" . $row['s_no'] ."</td>
<td> <label for='student_name'><textarea name='student_name' >".$row['student_name']."</textarea></label></td>
<td> <textarea name='roll_no'>".$row['roll_no']. "</textarea></td>
<td> <textarea name='company'>".$row['company']. "</textarea></td>
<td> <textarea name='contact_no' >".$row['contact_no']. "</textarea></td>
<td> <textarea name='email'>" .$row['email']. "</textarea></td>
</tr>
<input type='text' name='batch_name' disabled='disabled' size='7' value=" .$_POST['batch_name']. ">
<p align='center'><button id='submit' type='submit'>Update</button></p>
</form>";
}
I'have taken the datas from the database and put as default into the texareas and thus it cab de edited. So i planned to USE UDPDATE query to make the alternations like this:
<html>
<title>Alumini Update</title>
<head>
<?php
$con = mysql_connect("localhost","root","momsgift");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("alumini", $con);
mysql_query("UPDATE $_POST[batch_name] SET contact_no = $_POST[contact_no] WHERE roll_no = '2321'");
mysql_close($con);
?>
But while sending a query the data in the textarea doesnt loaded to the database ( BUt it redirects to the up.php page)
WHat may be the reason??
You are generating invalid HTML.
You cannot wrap a form around a table row without wrapping it around the entire table.
Your browser is error recovering by moving the form element. This is the most likely cause of the unexpected results.
Use a validator on your generated HTML.
In your MySQL update query you are only updating contact_no no other fields.
Also you have left your query open for SQL injections
$batch_number = mysql_real_escape_string($_POST['batch_name']);
$contact_no = mysql_real_escape_string($_POST['contact_no']);
$student_name = mysql_real_escape_string($_POST['student_name']);
$roll_no = mysql_real_escape_string($_POST['roll_no']);
$company = mysql_real_escape_string($_POST['company']);
$email = mysql_real_escape_string($_POST['email']);
mysql_query("UPDATE ('" . $batch_no. "')
SET contact_no = ('" . $contact_no . "'),
student_name = ('" . $student_name. "'),
company = ('" . $company . "'),
email = ('" . $email . "'),
WHERE roll_no = ('" . $roll_no . "')");
This (mysql_real_escape_string) won't solve every problem, and using PDO is a better method, but it's a very good stepping stone.
first write this and see the result,if it show's text of textarea it show's that text is sending in right way.and the problem is in ur sql code.
echo $_POST['contact_no'];
then you can echo the query and copy and run it in phpmyadmin and view error of sql.
//EXAMPLE 1
if (isset($_POST['update']))
{
$result = pg_query($db_con, "UPDATE mydbtable SET mydbrecord = '$_POST[my_var1]' WHERE mydbrecord_id = '$_POST[myfilterbyid_var]'");
if (!$result)
{
echo "Update failed!!";
}
else
{
echo "Update successfull!";
}
}
//EXAMPLE 2
<form name="display" action="" method="post">
<select name="mydropdown" action="test.php" method="post">
<?php
while($row = pg_fetch_assoc)
{
echo "<option id=\"{$row['result_var']}\">{$row['result_var']}</option>";
}
?>
</select>