form made with echo dosen't call php function - php

I have tried to make a ToDo list for a user. In the code below, wish adding button works fine and calls 'add_wish()' function but 'delete'/'update' button doesn't call relevant function. Rather call a file ''. Tried searching forums for hours. Why this is happening and how can I call relevent functions using this approch of extracting data from database. My code:
<body>
<?php
global $id, $adatabase;
include 'connect_to_database.php';
$adatabase = new database('localhost','root','');
function delete_wish($post_id) {
echo 'BLAH BLAH BLAH';
if(!empty($new_todo)) {
global $id,$adatabase;
$query = "DELTE FROM todolist WHERE post_id = '".$post_id."''";
if ($query_run = mysqli_query($adatabase->mysqli_link,$query)) {
get_user_todos($id);
} else 'Failed to add new wish.Please try again later!';
}
}
function update_wish($post_id) {
echo 'OKA';
}
function get_user_todos($user_id) {
global $id, $adatabase;
$id= $user_id;
echo $user_id;
$query = "SELECT todo,post_id FROM todolist WHERE user_id = '".$user_id."'";
if ($query_run = mysqli_query($adatabase->mysqli_link,$query)) {
?>
<div id="todo_list">
<table border="10" cellpadding="10">
<?php
while($query_data = $query_run->fetch_row()) {
echo '<tr>';
echo '<td>'.$query_data[0].'</td>';
echo "<td> <form method='post' action=\"<?php update_wish(".$query_data[1].");?>\"> <input type='submit' value='update'> </form> </td>";
echo "<td> <form method='post' action=\"<?php delete_wish(".$query_data[1].");?>\"> <input type='submit' value='delete'> </form> </td>";
echo '</tr>';
}
?>
</table>
</div>
<?php
}
}
function add_wish() {
global $id;
if(isset($_POST['new_todo'])) {
$new_todo = $_POST['new_todo'];
if(!empty($new_todo)) {
global $id,$adatabase;
$query = "INSERT INTO todolist (todo,user_id) VALUE ('".mysqli_real_escape_string($adatabase->mysqli_link,$new_todo)."','".$id."')";
if ($query_run = mysqli_query($adatabase->mysqli_link,$query)) {
get_user_todos($id);
} else 'Failed to add new wish.Please try again later!';
}
}
}
session_start();
if(isset($_SESSION['user_id'])) {
get_user_todos($_SESSION['user_id']);
?>
<form method="post" action=" <?php add_wish(); ?>">
<textarea rows="4" cols="8" name="new_todo"></textarea>
<input type="submit">
</form>
<?php
}else
header('Location: login.php');
?>
</body>

Related

$_SESSION variables "disappear" after form is submitted

I stored values from a form in SESSION variables but it seems that they are emptied after if(isset($_POST['submit']) even though I can echo them earlier in my code. The code runs and the insert works except for $toto and $tata which are empty.
In the code below _id, master_label, client_label are inserted correctly. And the target table fields match so the error does not come from there.
<?php
session_start();
[...]
echo "<form id='organization' action='?' method='POST' enctype='multipart/form-data' >" ;
echo "<select name='organization' onchange='this.form.submit()'>"; //
echo '<option value="">Select ORGANIZATION</option>';
while ($row=mysqli_fetch_array($result00)) {
echo '<option value="'.$row['company_id'].'">'.$row['company_id'].'</option>';
}
echo "</select>";
echo "</form>";
$cie_ticker = $_POST['organization'] ;
$_SESSION['company_id'] = $cie_ticker ;
$sql="(SELECT company_id, databasefile, company_name FROM `settings` WHERE company_id='$cie_ticker') LIMIT 1";
$result=mysqli_query($connect,$sql) or die('Could not execute the query ' . mysqli_error()) ;
$data_bis=$result->fetch_array() ;
$_SESSION['selected_cie_id'] = $data_bis['company_id'];
$_SESSION['selected_cie_name'] = $data_bis['company_name'];
<form id='demoForm' action="?" method="POST" enctype="multipart/form-data" target="_top">
<?php
$file = fopen('./company/'.$cie_ticker.'/'.$_SESSION['selected_cie_db'], "r") ; // $file = fopen('./company/'.$_SESSION["company_id"].'/'.$_SESSION['selected_cie_db'], "r") ;
$headers=fgetcsv($file, 1000, "|");
fclose($file);
?>
<table id="user_table">
<tr><th>HEADERS </th><th>MASTER DB HEADERS</th></tr>
<?php foreach ($headers as $entete) {
$query01="SELECT master_label FROM `mastertable`";
$result01=mysqli_query($connect,$query01); ?>
<tr id="<?php echo $entete;?>">
<td> <?php echo $entete ?></td>
<td id="<?php echo $row['_id'];?>">
<?php
echo "<br>";
echo "<select name=".$entete.">";
echo '<option value="MASTER DATA">Select MASTER DATA</option>';
while ($row=mysqli_fetch_array($result01)) {
echo '<option value="'.$row['master_label'].'">'.$row['master_label'].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<?php } ?>
</table>
<input id="checkBtn" type="submit" name="submitbutton" value="SAVE" class="button"/>
</form>
if(isset($_POST['submitbutton'])) {
$toto = $data_bis['company_id'] ;
$tata = $data_bis['company_name'];
$selected=$_POST;
foreach($selected as $x => $x_value) {
$query= $connect->prepare("INSERT INTO `mytable` (_id, master_label, client_label, org_label, client_id) VALUES ('',?,?,?,?) ");
$query->bind_param('ssss',$x_value, $x, $toto, $tata );
$query->execute();
}
}
?>
I have found the answer:
In this case one must add hidden input for the $_SESSION variables otherwise they were lost after submitting the form.

Button function for all fetch row

I am doing project for my university. I create a page where user can send friend request. Here I fetch data from another table and put button for each row data.
My problem is that when one button click other row button also was change to friend request. I need a solution for it.
How to make one add friend request button is equal to one row id and how to avoid other button affected whenever click particular row.
My code is included below. I hope you guys will help me. Thanks in advance.
<?php
session_start();
$_SESSION['myid'];
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID ORDER BY
tutor_register.register_ID='".$_SESSION['myid']."'desc";
$result= mysqli_query($mysqli,$sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
$username = $row['username'];
$profile = $row['profile'];
$email = $row['email'];
$address=$row['address'];
$gender=$row['gender'];
$main_subject=$row["main_subject"];
$subject_add=$row["subject_add"];
$rate_main=$row["rate_main"];
$rate_add=$row["rate_add"];
$qualification=$row["qualification"];
?>
<table><form method="post">
<tr class="border_bottom">
<td height="230"><img src='<?php echo $profile;?>'width="200" height="200"/> </td><td><td></td></td>
<?php
if($register_ID == $_SESSION['myid']){
?>
<td><label>Your Profile</label></td>
<?php
} else {
?>
<form method="post">
<td><button class='friendBtn unfriend' name="" data-type="unfriend">Unfriend</button>
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/></td> </form>
<?php
}
}
?>
</tr>
</div>
</table>
</form>
<?php
if(isset($_POST['id']) ) {
$user_id = $_SESSION['myid'];
$friend_id = $_POST['id'];
$sql="INSERT INTO friends(user_id,status,friend_id)" ."VALUES('$user_id','yes','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['id']=$row['id'];
} else {}
}
}
?>
</body>
</html>
You need to replace the following block in your code:
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes'){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>
With the one mentioned below. This will solve your problem.
<input type="submit" name="addfriend" data-type='addfriend' id="addfriend" value="<?php
if($_SESSION['status'] == 'yes' && $row['register_ID']==$_SESSION['id']){
echo 'Request Sent';
}
else {
echo 'Addfriend';}
?>" data-uid=<?php echo $row['register_ID'];?>/>

telephone directory update issue

I was programming something and I faced the problem. I was wondering where is the problem, because my code stop working after mysql_query("UPDATE ...") part. Here is the code, I hope someone will help me.
<?php include("/includes/template/header.php"); ?>
<section>
<form action="" method="post">
<input type="post" name="ime" placeholder="Ime"><br>
<input type="post" name="prezime" placeholder="Prezime"><br>
<input type="post" name="broj" placeholder="Broj telefona"><br>
<input type="post" name="adresa" placeholder="Adresa"><br>
<input type="submit" name="submit" value="Trazi">
</form>
<?php
include("includes/config.php");
if(isset($_POST['submit']))
{
if(!empty($_POST['ime']) && !empty($_POST['prezime']))
{
$trazeno_ime = $_POST['ime'];
$trazeno_prezime = $_POST['prezime'];
$query = "SELECT id, broj_telefona, adresa FROM korisnici WHERE ime = '$trazeno_ime' AND prezime='$trazeno_prezime'";
if ($query_run = mysql_query($query))
{
if(mysql_num_rows($query_run)!=NULL)
{
$query_row = mysql_fetch_assoc($query_run);
$id = $query_row["id"];
$brojtel = $query_row["broj_telefona"];
$adresa = $query_row["adresa"];
echo "<form action=\"\" method=\"post\">";
echo "<input type=\"post\" name=\"ime1\" value=\"$trazeno_ime\"><br></br>";
echo "<input type=\"post\" name=\"prezime1\" value=\"$trazeno_prezime\"><br></br>";
echo "<input type=\"post\" name=\"broj1\" value=\"$brojtel\"><br></br>";
echo "<input type=\"post\" name=\"adresa1\" value=\"$adresa\"><br></br>";
echo "<input type=\"submit\" name=\"submit1\" value=\"Promijeni\">";
echo "</form>";
if(isset($_POST['submit1']))
{
if(!empty($_POST['ime1']) && !empty($_POST['prezime1']) && !empty($_POST['broj1']) && !empty($_POST['broj1']) && !empty($_POST['adresa']))
{
$novoime = $_POST['ime1'];
$novoprezime = $_POST['prezime1'];
$novobroj = $_POST['broj1'];
$novoadresa = $_POST['adresa1'];
mysql_query("UPDATE korisnici SET ime='$novoime', prezime='$novoprezime', broj_telefona='$novobroj', adresa='$novoadresa' WHERE id=$id") or die(mysql_error());
echo "Uspješno promijenjeni podaci";
}
else
{
echo "Morate unijeti sva polja";
}
}
else
{
echo "Glupost";
}
}
else
{
echo "Nema korisnika u bazi";
}
}
else
{
echo "Hahu";
}
}
else
{
echo "Unesi podatke";
}
}
?>
</section>
</div>
</body>
You need to add quotes to your id statement see below.
"UPDATE korisnici SET ime='$novoime', prezime='$novoprezime', broj_telefona='$novobroj', adresa='$novoadresa' WHERE id='$id'"

View customer info on select change

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.

function running in foreach loop

thank you for taking time to look at this. I have been dealing with this annoying foreach loop. Here is what I am trying to do.
I have the first page "form.php".
On this page I have check boxes. Each check box is generated from a database table. Here is the code:
<?php
include("config.php");
$mysqli = new mysqli($host, $db_uname, $db_pass, $db);
$query = "SELECT * FROM `plugins` WHERE 1";
if ($result = $mysqli->query($query)) {
echo '<form action="test.php" method="post">
<input name="gname" placeholder="Group Name..."/>
<table width="200">
';
while ($row = $result->fetch_assoc()) {
echo '<tr><td>
<label>
<input type="checkbox" value="'.$row["plugin"].'" name="checkbox[]">
'.$row["plugin"].'
</label>
</td></tr>';
}
echo '
</table>
<select name="permplugin">
<option>Select One...</option>';
$query2 = "SELECT * FROM `permission_types` WHERE 1";
if ($result2 = $mysqli->query($query2)) {
echo '<h3>Select Permission format below</h3><hr />';
while ($row2 = $result2->fetch_assoc()) {
echo '
<option value="'.$row2["plugin_name"].'">'.$row2["plugin_name"].'</option>';
}
echo '
</select>
<br />
<input name="" type="reset"><input name="" type="submit">
</form>';
}
}
?>
Now after that it sends the checked boxes to "test.php"
here is the code for that:
<?php
if(!empty($_POST['checkbox']) || !empty($_POST['select']) || !empty($_POST['gname'])) {
echo '<h1>'.$_POST['gname'].'</h1>';
$check1 = $_POST['checkbox'];
foreach($check1 as $check) {
include "functions.php";
checkboxes($check);
}
echo '<h3>Selected Permission format below</h3><hr />';
echo $_POST['permplugin'];
} else {
echo "please select atleast one plugin.";
}
?>
The functions page code looks like this:
<?php
//all functions are here.
function checkboxes($check){
$mysqli_perm = new mysqli("localhost", "uname", "pword", "tcordero_permnodes");
$query_perm = "SELECT * FROM permission_nodes WHERE plugin = `$check`";
if ($result_perm = $mysqli_perm->query($query_perm)) {
echo $check;
/* fetch associative array */
while ($row_perm = $result_perm->fetch_assoc()) {
echo $row_perm['node'].'<br />';
}
unset($check);
}
}
When I run the test.php I get this error:
Fatal error: Cannot redeclare checkboxes() (previously declared in C:\xampp\htdocs\TPYC\functions.php:3) in C:\xampp\htdocs\TPYC\functions.php on line 15
What am I doing wrong?
You need to take the include out of the foreach loop. Try this:
include "functions.php";
foreach($check1 as $check) {
checkboxes($check);
}

Categories