Getting my form data to post to mysql database - php

Pretty new to php/mysql and jquery, and I'm having trouble getting my form data to upload to my mysql db. I've tried a few different approaches and done my research, but none of the suggestions I've found online are working for me, which is why I'm posting here. So here's my most recent failed approach:
in my index file:
<head>
...
<script type="text/javascript">
$(document).ready(function() {
// Announcement form AJAX submit
$('#announcementForm').submit(function() {
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if (data.error) {
$('#error').css('display', 'block');
} else {
$('#note').show();
$('#error').hide();
$('#fields').hide();
}
}
});
return false;
});
});
</script>
</head>
<body>
...
<form class="dl_form" id="announcementForm" method="post">
<dl>
<dt>Announcement</dt>
<dd><textarea id="Announcement" sytle="width: 300px; height: 150px;" name="Announcement"></textarea></dd>
</dl>
<dl>
<dt>Announcement Type:</dt>
<dd><input type="radio" name="Type" value="schedule">Scheduling</input></dd>
<dd><input type="radio" name="Type" value="general">General</input></dd>
</dl>
<dl>
<dt></dt>
<dd><input type="submit" value="submit" /></dd>
</dl>
</form>
<div id="note">
<p>Announcement posted successfully!"</p>
</div>
<div id="error">You haven't completed all of the required fields</div>
And then in my ajax.php file I have (some lines have been replaced with "######" for security reasons):
<?php
//database credentials
$server = '######';
$username = '######';
$password = '######';
$database = '######';
$connect = mysql_connect($server, $username, $password ) or die(mysql_error.'error connecting to db');
//select database
mysql_select_db($database, $connect) or die(mysql_error.'error selecting db');
//$typeValue = $('input:radio[name=Type]:checked').val());
if (!empty($_POST)){
$Announcement = $_POST['Announcement'];
$Type = $_POST['Type'];
if (!empty($Announcement) && !empty($Type) )
{
//insert data into db
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
}else {
echo json_encode(array(
'error' => true,
'msg' => "You haven't completed all required fields!"
));
exit;
}
}
?>
Any help you guys can provide would be much appreciated.
Thanks
UPDATE IN RESPONSE TO Jay Blanchard:
I just ran the console in my browser. The only error I'm getting is:
SCRIPT1004: Expected ';'
in reference to the first line of my JS:
$function() {
...
UPDATE 2:
Just updated my code to reflect my most recent changes...before I could at least trigger the submit click even and the fields would empty, indicating that at least something was happening. With my new round of changes however, not even that triggers, so I'm still pretty stuck

In your php you've made a mistake with your echo statement its not jason_encode instead its json_encode.
Additionally
Also you Should remove AnnouncementID from your query if in database it is auto increment, because db will warn you for incorrect integer value for column AnnouncementID.
EDIT: In your php part in statement
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement"')") or die(mysql_error());
You are forgetting a concatenation operator . after '".$Announcement which should be
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
and in your jquery instead of
$function() {
use
$(document).ready(function(){

Related

Json data not saved to DB in PHP

I am trying to make a functionality where I am sending Name and Age using ajax. The same is gathered by PHP and then stored to DB. I think I am doing it correctly but data not saved in database. Can someone help me out?
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('button').click(function(){
$.ajax({
url: 'addData.php',
type: 'POST',
dataType: "json",
data: {
name: $('#name').val(),
age: $('#age').val(),
}
})
});
});
</script>
</head>
<body>
<input id="name" type="text" />
<input id="age" type="text" />
<button>Click</button>
</body>
</html>
PHP
<?php
//Parameters for connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test1";
//Reading json
$data_back = json_decode(file_get_contents('php://input'));
// set json string to php variables
$name = $data_back->{"name"};
$age = $data_back->{"age"};
// Create Connection
$conn = new mysqli($servername, $username, $password, $dbname);
//Creating Query
$sql = "INSERT INTO table1 (name, age) VALUES ($name, $age)";
//Running Query
$conn->query($sql);
//Closing Connection
$conn->close();
?>
ERROR
Even though you're sending data with jquery as json, php is still recieving it as a $_POST object. So, this should work:
$name = $_POST['name'];
$age = $_POST['age'];
I think your object $data_back is empty because of errors in parsing of data by function json_decode. You should try to use var_dump($data_back); exit; after json_decode or more advanced methods such as debugging.
I believe this is the proper way to access data post json_decode
$name = $data_back->name;
I also recommend looking into prepared statements for the database query execution...Ok, I HIGHLY recommend you look into it.
Edit: Maybe try this as well: Replace file_get_contents() with $_POST;

Insert Into MYSQL DB using jquery/ajax 500 internal server error

I'm inserting radio checked data values into mysql db with php/jquery and ajax while inserting values i'm getting internal server 500 error...
Any help is appreciated Thanks!
Html Code
<div>
<input class="radio_div_clicked" value="<?php echo $row['name'];?> name="radio_section" id="<?php echo $row['id'];?>"/>
<p><?php echo $row['name'];?></p>
<button id="add_feed">Add</button>
</div>
JQUERY CODE
<script type="text/javascript">
$('body').delegate('#add_feed','click',function(){
var radio_div_clicked = $('input:radio[name=radio_section]:checked').val();
$.ajax({
type:"POST",
url:"index.php",
cache: false,
data:{
insert_section:1,
radio_div_clicked:radio_div_clicked
},
success:function(data)
{
alert('Successfully Inserted Into Table');
}
});
}
});
</script>
PHP code
<?php
$con = #mysql_connect('localhost','root','') or die('failed to connect server');
$db = mysql_select_db('demo',$con) or die('failed to select db');
if(isset($_POST['insert_section']))
{
$radio_div_clicked = mysql_real_escape_string($_POST['radio_div_clicked']);
$sql = mysql_query("insert into test(name) values($radio_div_clicked)";
if($sql)
{
echo "Successfully Inserted Into Table";
}
else
{
echo "Failed To Insert Value Into Table"
}
}
?>
<?php
mysql_close ($con);
?>
Mysql query values($radio_div_clicked)"; did't closed properly, should be
$sql = mysql_query("insert into test(name) values('".$radio_div_clicked."')");
If you're using chrome, click on network tab, and click the requested link. Then, again click on preview or response header. Usually the details errors showing up there.

referencing an image from php

I have a function on a website where I have a img reference leading to a php page
<img src="selectimage.php?uid=21312412">
which I need to return an image and update a database file
<?php
$servername = "localhost";
$username = "webz";
$password = "BLAH";
$dbname = "contactlist";
$readid = $_GET["uid"];
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "UPDATE emails SET `read`='1' WHERE `id`='" .$readid. "'";
if ($conn->query($sql) === TRUE) {
echo "<img src='logo11w.png'>";
}
$conn->close();
?>
I figured this would not work as I am referencing a php page in which is referencing the HTML tag
While this is updating my database it is not displaying the image.
how do I make this php file send the image logo11w.png to that img tag
Further note : include or other methods of including this code on the page loading are out of the question because this procedure may be called from a off-server source.
Store user id in one hidden field
You can use ajax for get respone back from php page after updating value in database
<input type="hidden" id="userid" value="user_id_value">
<input type="button" id="getimage" value="GET IMAGE">
<div id="u_img"></div>
$(document).ready(function(){
$('#getimage').click(function() {
var uid = $('#userid').val();
var datastring = "uid="+uid;
$.ajax({
type: "POST",
url: "php_page.php",
data: datastring,
cache: false,
success: function(result) {
$('#u_img').append(result);
}
});
});
});
The most effective method for what I am trying to do turns out to be:
...
if ($conn->query($sql) === TRUE) {
header('Content-Type: image/jpeg');
echo file_get_contents('https://www.google.com/images/srpr/logo11w.png');
} else {
echo "Error updating record: " . $conn->error;
}
...

How do I show the PHP variable value in the JavaScript pop-up?

I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.

Why is PHP mysql_insert_id() returning zero?

I have the following code. The $last_id is always showing zero. I do have a column in the "source" table that has auto-increment id. What is the problem with this code?
index.php:
<?php
// connect to the database
include('connect-db.php');
$last_id = mysql_insert_id($connection);
$content = "Please type your content here!";
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: <?php echo $last_id;?>");
}
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
connect-db:
<?php
$server = 'localhost';
$user = 'mumbo';
$pass = 'mumbo123';
$db = 'jumbo';
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
try this as submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
echo mysql_insert_id();
}
?>
and in the javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: " + data);
}
);
return false;
});
});
</script>
This line is computed when the original page loads:
alert("Your ID: <?php echo $last_id;?>");
So it's effectively:
alert("Your ID: 0");
Since all you've done at that point is connect, there is no insert id. I'm not familiar with jquery, but presumably the data parameter to your callback should contain data about the response from submit.php. You need to make submit.php return the ID, then get that data through whatever means in jquery, and display it.
Edit: actually, it looks like what you're doing can't really do what I said, anyhow.
http://api.jquery.com/submit/
You're setting up a handler which is run whenever the form is submitted - however, this is before the submit actually happens, so you can't actually get the ID there. Your options are to use something like XmlHttpRequest to make an asynchronous call, or have this popup on the submit.php page.
First of all do not use mysql, use mysqli or pdo, mysql is a deprecated system and should not be used. It is not secure and can be hacked easily.
Second, mysql_insert_id only works if you call it directly after the insert...
AKA
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
$last_id = mysql_insert_id();
echo $last_id
mysql_close($connection);
then your jquery must say
alert("Your ID: "+data);
The function data that is returned is whatever you echo from your script. Jquery retrieves it in whatever callback variable you set (data) and then you can use it.

Categories