jQuery not receiving part of data - php

I'm creating testing application for sending and receiving messages using PHP/jQuery and AJAX. My code works with no problems when I comment out this part of code:
$("#sendUser").submit(function(){
return false;
});
If I leave this part uncommented then jQuery don't receive value from <select> tag. Can someone tell me how to solve this. This is my full code:
<form action="send_toUser.php" method="post" id="sendUser">
<label>Title: </label>
<input type="text" name="title" id="title"><br>
<label>To: </label>
<select name="user" id="user">
<?php $getData = $mysqli->query("select * from login");
while($row = $getData->fetch_assoc()):
?>
<option><?php echo $row['username']; ?></option>
<?php endwhile; ?>
</select><br>
<label>Message:</label><br>
<textarea name="content" id="content"></textarea><br>
<input type="submit" value="Send" id="sendToUserButton">
<label id="outputLabel" hidden></label>
</form>
send_toUser.php
<?php
session_start();
include 'functions.php';
protect();
$title = $_POST['title'];
$content = $_POST['content'];
$user = $_POST['user'];
$con = new mysqli("localhost", "root", "alen", "loginregister") or die($con->error);
$queryReceiver = $con->query("select * from login where username = '$user'");
$idReceiver = $queryReceiver->fetch_assoc();
$idReceiver = $idReceiver['user_id'];
$queryUser = $con->query("select * from admin where username='admin'");
$idUser = $queryUser->fetch_assoc();
$idUser = $idUser['id_admin'];
date_default_timezone_set('UTC');
$date = date('Y-m-d');
$con->query("insert into message values('', '$idReceiver', '$idUser', '$title', '$content','', '$date')") or die("Error while sending!");
echo "Message sent";
?>
script.js
$("#sendToUserButton").click(function(){
$.post("send_toUser.php"),
{"title" : ("#title").val(), "user" : ("#user").val(), "content" : ("#content").val()},
function(data){
$("#outputLabel").html(data);
}
});
$("#sendUser").submit(function(){
return false;
});

Related

getting data by id from database after submitting to another page

I m trying to get data on another page by id which is on showdetails.php page.but i m unable to please help.
Showdetails.php
this page shows details of user with id and button which will allow user to edit details on another page
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
</head>
<body>
<?php
require('database.php');
?>
<h1>User Lists</h1>
<?php
$select = "SELECT id, firstname, lastname FROM signup";
$selectdata = $conn->query($select);
if ($selectdata->num_rows > 0){
while($row = mysqli_fetch_array($selectdata)) {
$id = $row['id'];
$first = $row['firstname'];
$last = $row['lastname'];
?>
<form method="get" action="editdetails.php">
<p><b>ID: <?php echo $id; ?></b></p>
<p>Name: <?php echo $first; ?> <?php echo $last; ?></p>
<?php
$edit = "SELECT id FROM signup WHERE id= '" .$id. "'";
$selectedit = $conn->query($edit);
?>
<p><input type="submit" name="display" value="Edit Details"></p>
</form>
<?php
}
}
?>
</body>
</html>
editdetails.php
On this page, user will be able to edit details, and i want details by id
<!DOCTYPE html>
<html>
<head>
<title>Edit User Details</title>
</head>
<body>
<?php
require('database.php');
$select = "SELECT firstname, lastname, age, phone_no, age, username, password FROM signup";
$selectdata = $conn->query($select);
if ($selectdata->num_rows > 0){
$row = mysqli_fetch_array($selectdata);
$first = $row['firstname'];
$last = $row['lastname'];
$age = $row['age'];
$phone_no = $row['phone_no'];
$username = $row['username'];
$password = $row['password'];
}
?>
<?php
if (isset($_POST['update'])) {
# code...
$first = mysqli_real_escape_string($conn, $_POST['first']);
$last = mysqli_real_escape_string($conn, $_POST['last']);
$age = mysqli_real_escape_string($conn, $_POST['age']);
$phone = mysqli_real_escape_string($conn, $_POST['phone_no']);
$username = mysqli_real_escape_string($conn, $_POST['user']);
$password = mysqli_real_escape_string($conn, $_POST['pass']);
$update = "UPDATE signup SET firstname= '$first', lastname= '$last', age= '$age', phone_no = '$phone', username = '$username', password = '$password' WHERE id= '$id'";
$updatedata = $conn->query($update);
if ($updatedata) {
# code...
echo $status = "Details Updated";
}
else {
# code...
echo $status = "Not Updated";
}
}
if (isset($_POST['delete'])) {
# code...
$delete = "DELETE FROM signup WHERE firstname = $first";
$deletedata = $conn->query($delete);
if ($deletedata) {
# code...
echo $status = "Details Deleted";
}
else {
# code...
echo $status = "Not Deleted";
}
}
?>
<h1>Edit Details</h1>
<form method="post" action= "<?php htmlspecialchars($_SERVER['PHP_SELF']) ?>">
<p>FirstName: <input type="text" name="first" value="<?php echo $first; ?>"></p>
<p>LastName: <input type="text" name="last" value="<?php echo $last; ?>"></p>
<p>Phone no: <input type="number" name="phone_no" value="<?php echo $phone_no; ?>"></p>
<p>Age: <input type="number" name="age" value="<?php echo $age; ?>"></p>
<p>User: <input type="text" name="user" value="<?php echo $username; ?>"></p>
<p>Password: <input type="password" name="pass" value="<?php echo $password; ?>"></p>
<p><input type="submit" name="update" value="Update">
<input type="submit" name="delete" value="Delete"></p>
</form>
<p><?php echo $status; ?></p>
</body>
</html>
Thank You.
Add in your HTML form a hidden input, like so:
<input type="hidden" name="id" value="<?php echo $id; ?>">
Then in your editdetails.php file you can access it with: $_GET["id"].
Update:
Add the hidden input to the form in Showdetails.php.
Then in editdetails.php add at the top of the page $id = (int)$_GET["id"];
Then add to your SELECT query in editdetails.php a WHERE statement for selecting the correct user:
$select = "SELECT ... FROM signup WHERE id = $id";
For the update query you are then good to go since you are already using there WHERE id = $id. (but before your $id variable was not defined)

Session Variable not accessible when opening website on other device [php code]

I have local host website. Connected two devices to a hotspot and accessing the website using the ip of the server. All the pages open properly but the session variable is not recognised as "Undefined Index" error throws up.
While when I access the same on the localhost I donot face this issue.
I have used session_start() in all the files.
Have the code snipped of Login.php
<?php
session_start();
?>
<html>
<head><title>LOGIN</title></head>
<body>
<form action= "Dashboard.php" method = "POST">
<br/>Name: <input type = "text" name = "name">
<br/>Password: <input type = "password" name = "password">
<br/><input type="submit" name = "submit" value = "submit"> or Register
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$password = $_POST['password'];
$connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");
$query = mysqli_query($connect,"SELECT * FROM users WHERE Name = '$name' and Password='$password'");
$count = mysqli_num_rows($query);
if($count == 1){
$_SESSION['username'] = $name;
echo "Login Successful";
}else{
echo "Invalid Login Credentials";
}
}
?>
After login Dashboard.php
<?php
session_start();
?>
<html>
<head><title>Dashboard</title></head>
<body>
<form action= "" method = "POST">
<?php echo "Welcome ".$_SESSION['username'].".<br>";
?>
<br/>Sex: <select name="sex"> <option value ="Male">Male</option> <option value = "Female">Female</option></select>
<br/>Age: <select name="years">
<?php
for($i=1; $i<=50; $i++)
{
echo "<option value=".$i.">".$i."</option>";
}
?>
<option name="years"> </option>
</select>
<br/>Citizen: <select name="citizen"><option value="Singaporean">Singaporean</option><option value="International">International</option></select>
Click to Download!
<br/><input type="submit" name = "submit2" value = "Save Changes"> orLogout
</form>
</body>
</html>
<?php
if(isset($_POST['submit2'])){
$name = $_SESSION['username'];
$connect = mysqli_connect("localhost","root", "","nets") or die("Couldn't connect to database");
$query1 = mysqli_query($connect,"SELECT Sex,Age,Citizen FROM users where Name = '$name'");
while ($row = mysqli_fetch_row($query1))
/* {
echo "Details Entered in Database:".".<br>";
echo "<br>";
echo "Name:".$_SESSION['username'].".<br>";
echo "Sex:".$row[0].".<br>";
echo "Age:".$row[1].".<br>";
echo "Citizen:".$row[2].".<br>";
}*/
$sex = $_POST['sex'];
$years = $_POST['years'];
$citizen = $_POST['citizen'];
$query2 = mysqli_query($connect, "UPDATE users SET Sex = '$sex', Age='$years', Citizen='$citizen' WHERE Name = '$name'");
echo "Saved changes";
}
?>
Please suggest
Your form has the action "Dashboard.php", so that script will handle the submission of your login form.
In other words, the logic inside the code block for the if statement if(isset($_POST['submit'])){ is probably not executed, so your session variable isn't set.
You can set the action to "Login.php" or leave it blank to let Login.php handle the login, then you can redirect to Dashboard.php if you desire and the session variable should be set.
Do mind that if you want to redirect using PHP, it must be done before the HTML. Otherwise it won't work.

Search User by Last Name PHP

Yahallo! I have a problem in searching the user in the database and displaying them into the textfields. I have set everything to query and search the user by typing the lastname but it gives me an error
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' .
<?php
$host = "localhost";
$user = "root";
$password ="";
$database = "ntmadb";
$id = "";
$firstname = "";
$lastname = "";
$username = "";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
// get values from the form
function getPosts()
{
$posts = array();
$posts[0] = $_POST['id'];
$posts[1] = $_POST['firstname'];
$posts[2] = $_POST['lastname'];
$posts[3] = $_POST['username'];
return $posts;
}
// Search
if(isset($_POST['search']))
{
$data = getPosts();
$search_Query = "SELECT * FROM members WHERE lastname = $data[2]";
$search_Result = mysqli_query($connect, $search_Query);
if($search_Result)
{
if(mysqli_num_rows($search_Result))
{
while($row = mysqli_fetch_array($search_Result))
{
$id = $row['id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$username = $row['username'];
}
}else{
echo 'No Data For This Id';
}
}else{
echo 'Result Error';
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="index44.php" method="post">
<input type="text" name="id" placeholder="Id" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="firstname" placeholder="First Name" value="<?php echo $firstname;?>"><br><br>
<input type="text" name="lastname" placeholder="Last Name" value="<?php echo $lastname;?>"><br><br>
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>"><br><br>
<div>
<!-- Input For Edit Values -->
<input type="submit" name="update" value="Update">
<!-- Input For Find Values With The given ID -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>
Can someone assist in fixing it? Thank you!
Try below query.
$search_Query = "SELECT * FROM members WHERE lastname = '".$data[2]."'";
Try this:
$temp_lastname = $data[2];
$search_Query = "SELECT * FROM `members` WHERE `lastname` = '$temp_lastname'";

Can't get ID to insert into database from HTML Form (using PHP)

Right now I am trying to create a edit form for my forum, and while I CAN get it to edit, it does not insert an ID to the database (rendering it 0 and thus faulty), the ID field have Auto increment and I've double checked it is the primary field. Tried looking over it many times, but there's got to be something I am missing.
The DB connection:
<?php
error_reporting(E_ALL);
session_start();
$host = 'HOSTNAME';
$dbusername = 'USERNAME';
$dbpassword = 'PASSWORD';
$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("<b>Could not connect to database server</b>");
$anslutning->select_db('DATABASE NAME') or die("<b>Could not connect to the specified database</b>");
?>
The form where you edit the post ($edit in this scenario is the ID it grabs when clicking "edit" on a post), as well as where I try to update the database field.
<?php
if(isset($_GET['edit'])) {
// If click on "edit"
$edit = $_GET['edit'];
// The post-editing ID
$getEditData = $anslutning->prepare("SELECT postId, title, content FROM tblPosts WHERE postid='$edit' LIMIT 1");
$getEditData->bind_result($postId, $title, $content);
$getEditData->store_result();
$getEditData->execute();
while($row = $getEditData->fetch()) {
echo '
<div class="editForm">
<form action="index.php" method="POST">
<input type="hidden" name="author" value="'.$_SESSION['loggedIn'].'">
<input type="hidden" name="edit" value="'.$edit.'">
Title: <input type="text" name="new_title" value="'.$title.'"> <br /> <br />
Content: <textarea name="new_content"> '.$content.' </textarea> <br /> <br />
<input type="submit" name="editPost">
</form>
</div>
';
}
}
// Issue(s): Editing a post does not send postId/edit(id) to database
if(isset($_POST['editPost'])) {
$edit = $_GET['edit'];
$author = $_POST['author'];
$new_title = $_POST['new_title'];
$new_content = $_POST['new_content'];
$updatePost = $anslutning->prepare("UPDATE tblPosts SET postId=?, author=?, title=?, content=?");
$updatePost->bind_param("isss", $edit, $author, $new_title, $new_content);
$updatePost->execute();
echo 'Post updated. Redirecting..';
sleep(1);
echo '<script> window.location.href = "index.php?forum=1" </script>';
}
?>
Change
$edit = $_GET['edit'];
to
$edit = $_POST['edit'];

How can I update MySQL with PHP, using the following syntax:

<?php
//connect to server
$connect = mysql_connect("localhost","name","password");
//connect to db
mysql_select_db("complexm_pondlife", $connect);
//query the db
$query = mysql_query("SELECT * FROM frogs");
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<button onclick="show()">SHOW DATA</button>
<p id="clip"style="visibility: hidden">
<?php
WHILE($rows = mysql_fetch_array($query)):
$name = $rows['name'];
$age = $rows['age'];
$sound = $rows['sound'];
$id = $rows['id'];
?>
<?php
echo $id.") "."Name: ";
?>
<form action = "" method = "post">
<input type="text" id="name" value='<?=$name?>'>
<input type="submit" name="update_db" value="Update">
</form>
<?php
echo "Age: "."$age<br><br>";
echo "Sound: "."$sound<br><br>";
echo "___________<br><br>";
endwhile;
?>
</p>
<?php
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = '$name'");
}
if(isset($_POST['update_db'])){
echo upload();
}
?>
<script>
function show(){
document.getElementById('clip').style.visibility="visible";
}
</script>
This code gives me: Notice: Undefined variable: name in /home1/complexm/public_html/projects.php on line 70
I dont know why though. So if anyone can tell me i would like to know. If the syntax is wrong please tell me!
This answer is based on your original post and not marking it as an edit, should anyone wonder.
The reason why your upload() function is failing, is because you haven't included the mysql_query() function, along with a few missing parts. (Parts, being quotes/brackets).
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = 'TreeFrog'");
}
A word of advice though:
Your present code is open to SQL injection.
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
also or die(mysql_error()) to mysql_query().
Edit:
To fire up your function using a PHP method, I recommend you change the
<input type="submit" onclick="update()"> to
<input type="submit" name="update_db" value="Update"> and wrapping an isset() around it.
I.e.:
<?php
function upload(){
mysql_query("UPDATE frogs SET name = '$name' WHERE name = 'TreeFrog'");
}
if(isset($_POST['update_db'])){
echo upload();
}
?>
However, you will need <form></form> tags around your form's element(s) and a post method.
<form action = "" method = "post">
<input type="text" id="name" value='<?=$name?>'>
<input type="submit" name="update_db" value="Update">
</form>
Edit #2:
This is a mysqli_ method, please change the DB credentials to match yours if they do not match.
I had to remove the upload() function, it was giving me too much trouble.
A hidden input has been added in the form, which is essential to doing updates like these.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//connect to server
$DB_HOST = 'localhost';
$DB_USER = 'name';
$DB_PASS = 'password';
$DB_NAME = 'complexm_pondlife';
$link = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($link->connect_errno > 0) {
die('Connection failed [' . $link->connect_error . ']');
}
//query the db
$query = mysqli_query($link,"SELECT * FROM frogs");
?>
<button onclick="show()">SHOW DATA</button>
<p id="clip"style="visibility: hidden">
<?php
WHILE($rows = mysqli_fetch_array($query)):
$name = $rows['name'];
$age = $rows['age'];
$sound = $rows['sound'];
$id = $rows['id'];
?>
<?php
echo $id.") "."Name: ";
?>
<form action = "" method = "post">
<input type="text" id="name" name="thename" value="<?php echo $name; ?>">
<input type="hidden" name="the_id" value="<?php echo $id; ?>">
<input type="submit" name="update_db" value="Update">
<br>
</form>
<?php
echo "Age: "."$age<br><br>";
echo "Sound: "."$sound<br><br>";
echo "___________<br><br>";
endwhile;
?>
</p>
<?php
if(isset($_POST['update_db'])){
$theid = stripslashes($_POST['the_id']);
$theid = mysqli_real_escape_string($link,$_POST['the_id']);
$thename = stripslashes($_POST['thename']);
$thename = mysqli_real_escape_string($link,$_POST['thename']);
$results= mysqli_query($link, "UPDATE frogs SET name = '$thename' WHERE id = '$theid'");
}
?>
<script>
function show(){
document.getElementById('clip').style.visibility="visible";
}
</script>
You can also redirect to the same page by adding this at the top:
<?php
ob_start();
?>
then adding this after your query:
if($results){
header("Location: http://www.yoursite.com/update_frogs.php");
}

Categories