mySQL insert statement NOT working? - php

I've been looking around for an answer. I've been cross-referencing my code with others. And I don't seem to see any blatant errors...
My database does not update, my database does nothing. Oh and the page also does nothing too...... It's frustrating because, I'm just using notepad ++ and can't pinpoint the error. I'm using XAmpp as well, and, all the values match the ones I have made.
The .post statement (Using jQuery 1.7.1):
//Make sure DOM is loaded before running jQuery based code: [STATIC CODE]
$(document).ready(function(){
$('#uploadbtn').click(function() {
//Parse name and song.
var name = $('#songname').val();
var song = $('#songupload').val();
$.ajax(
{
type: 'POST',
data: 'db/upload.php?name=' + name + 'song=' + song,
success: function(res) {
$('#nav-playlist').html(res);
}
}
)
});
});
Now here is my php file:
<?php
/*Connection to database.
First with mysql_connect (to log in). Then selecting the master database.
*/
echo "Upload.php accessed...";
$connection = mysql_connect("localhost", "root", "root") or die ( mysql_error() );
$database = mysql_select_db("betadb") or die( mysql_error() );
//Properties (to be inserted into database).
$name = mysql_real_escape_string($_POST["name"]);
$song = mysql_real_escape_string($_POST["song"]);
//Insertion formula for mySQL
$query = "INSERT INTO songs SET name= '$name' song='$song' ";
if (mysql_query($query)){
echo "Success";
}
else {
}
?>
ADDITIONAL NOTES:
the song table consists of id, name, song (in that order).
Song is the BLOB datatype, as it is used to store .mp3s

The problem is with the following line
data : 'db/upload.php?name='+name+'song='+song,
data should be an array containing the values, such as
var data
data["name"] = name
data["song"] = song
The $.ajax call is also missing the url parameter which is needed to carry out the request
url: 'db/upload.php'

Try to specify your column.
$query = "INSERT INTO songs (youcoulmn1,youcolumn2) VALUES ('$name', '$song')";
See also:
PHP MySQL Insert Into
Regards

$name = mysql_real_escape_string($_POST["name"]); //Assign to name & song variables.
$song = mysql_real_escape_string($_POST["song"]);
//Insertion formula for mySQL
$query = "INSERT INTO songs VALUES ('$name', '$song')";
$result = mysql_query($query, $connection) or die ("Unsucessful");

had better using SET, is more easier for some conditions, and for Jquery Command use $.ajax, you can try this one
for javascript / JQuery
$(function(){
$('#uploadbtn').click(function(){
var name = $('#songname').val();
var song = $('#songupload').val();
$.ajax({
type :'POST',
data : 'db/upload.php?name='+name+'song='+song,
success :function(res){
$('#nav-playlist').html(res);
}
});
});
});
and for Insert command in the php
$name = mysql_real_escape_string($_POST["name"]);
$song = mysql_real_escape_string($_POST["song"]);
$query = "INSERT INTO songs SET name='$name' song='$song'";
if(mysql_query($query)){
// some process if success
}else{
// some proses if not
}
use mysql_real_escape_string to filtering data before insert to database

in order to debug it
1) do print_r($_POST); to check do you have anything to insert
2) then instead of
$result = mysql_query($query, $connection) or die ("Unsucessful");
do
$result = mysql_query($query, $connection) or die (mysql_error());
to get the exact error and search for the error fix

The single quotes around variables might be causing the problem.. check it..

As far as I remember, the line
$query = "INSERT INTO songs SET name= '$name' song='$song' ";
should be
$query = "INSERT INTO songs SET name= '$name', song='$song' ";
Pay attention to commas!
And also:
data: 'db/upload.php?name=' + name + 'song=' + song,
should be at least:
data: 'db/upload.php?name=' + name + '&song=' + song,
because there is no delimiter between fields right now.

Related

Implement Ajax for a PHP Function

I am trying to work implement ajax due to maximum site load which PHP causes. But I am not aware of where I am making a mistake here. it is an anchor tag, when it is clicked the status of the particular row should be changed to a string which is hard coded.
PHP WAY
USERDETAIL.PHP
Next
Then it triggers This (IGNORE SQL INJECTION)
if(isset($_GET['changeStatus'])){
$id = $_GET['changeStatus'];
$user=$_SESSION['user'];
$sql = "select * from productOrder where id = ".$id;
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result);
$sql = "update productOrder set prodStatus = 'Ready', By='".$user."' where id=".$id;
if(mysqli_query($conn, $sql)){
header("Location:USERDETAIL.php");
}
}
}
According to this way, it works neat, but the userdetail.php would refresh anyways which is a lot time consuming. Then tried AJAX way is below.
Next
and that hits to
$(document).ready(function() {
$(".changeStatus").click(function(event){
event.preventDefault();
var status = "Ready";
var id = $(this).attr('data-id');
$.ajax({
url : 'action.php',
method : 'POST',
data : {status : status , id : id},
dataType: 'html',
success : function(response){
console.log(response);
}
});
});
});
and in the action.php it is (IGNORE SQL INJECTION AGAIN)
if(isset($POST['prodStatus'])){
$status = $_POST['prodStatus'];
$id = $_POST['id'];
$sql = "update productOrder set prodStatus= '$status' where id=".$id;
$result = mysqli_query($conn, $sql);
if($result){
return 'Updated';
}
}
The output is nothing happens. in the console it is just adding int values. I know I am making a mistake, or understood AJAX in a wrong way. it is just one button click and the string in SQL should be updated without an input text / modal. Please suggest what should be improved?
Also instead of having a seperate action php for these actions, can I do all these in userdetail.php itself with Ajax? is it possible?
Thanks in advance.
As B_CooperA pointed out, $POST should be $_POST.
Also, in $.ajax script data object your property name is status and in action.php you are checking it by prodStatus.
Furthermore, you should check the errors PHP is throwing in your script by enabling error reporting: error_reporting(E_ALL);
It's better to separate ajax calls from your view files. You can create a Class to handle all of your ajax calls (You should also consider authenticating your calls as per your use cases).

Result Update Database from Flash

I want to update database with flash (text input)
Here is my php code
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$isi = isset($_POST['OutData']);
$query2 = "UPDATE materi SET isi='$isi' WHERE id = 1";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
?>
Here is my Actionscript 2
function SubmitData()
{
trace("Sending");
var OutData = new LoadVars();
text_morfologi.text = OutData.OutData;
filepath = "http://localhost/adaptasi/";
OutData.sendAndLoad(filepath + "editmorfologi.php", OutData, "POST");
}
btnsave.onRelease = function()
{
SubmitData();
btnedit.visible = true;
btnsave.visible = false;
};
But the result isi in database is '1' not the text that I input in the text field.
Thanks
You have some problems in your code :
ActionScript 2 :
To send data using a LoadVars object you have to attache it to that object as its properties, and if you want to receive a response from your server side script, you can use LoadVars.sendAndLoad() but if you want just to send that data without waiting for any response, you can use LoadVars.send().
Supposed that you will use sendAndLoad() function, so you code can be like this :
var url:String = 'http://www.example.com/update.php';
// the LoadVars object that will receive (load) a response from the server
var receiver:LoadVars = new LoadVars();
receiver.onLoad = function(success:Boolean)
{
if (success) {
trace(receiver.response); // gives for example : update successful
} else {
trace('error');
}
}
// the LoadVars object which will send (post) some data to the server
var sender:LoadVars = new LoadVars();
sender.id = txt_id.text;
sender.name = txt_name.text;
sender.sendAndLoad(url, receiver); // we don't set the method to POST because that's its default value
PHP :
As mentioned in many comments, the PHP's isset() function is used to verify if a variable is set and is not NULL and it returns a boolean value ( TRUE of FALSE ) which is when it's casting (converting) to a string will give you 1 for TRUE and `` (empty string) for FALSE.
In your case, and according to you, I think that as the the variable $_POST['OutData'] is apparently set, isset($_POST['OutData']) is true which will set the value of $isi to 1, so you will get :
$query2 = "UPDATE materi SET isi='1' WHERE id = 1";
but according to your posted code, I think that you should get :
$query2 = "UPDATE materi SET isi='' WHERE id = 1";
Returning now to our current example, we will get our two POST variables (id, and name) sent by the AS2 script to update the DB and then return a response if the data has been successfully updated or not :
<?php
if(isset($_POST['id'] && isset($_POST['name']))
{
$id = $_POST['id'];
$name = $_POST['name'];
mysql_pconnect('localhost', 'root', '');
mysql_select_db('my_db');
$query = "UPDATE users SET name = '$name' WHERE id = $id";
$result = mysql_query($query);
if($result){
echo 'response=update successful';
} else {
echo 'response=update failed';
}
}
?>
Of course here I tried just to give you a very simple example of a working code according to your current one. You should know that for your PHP side that the "mysql" extension was deprecated in PHP 5.5.0 and was removed in PHP 7, so you should think to use "mysqli" or "PDO" extensions, for more about that, take a look here, also don't forget to sanitize, validate and escape any user's data, ... and for the ActionScript side, maybe it's the time to start learning ActionScript 3 ...
Hope that can help.

PHP/MySQL - Not posting to database

This PHP script is meant to post a users name into a database but it doesnt seem to work properly. The project in unity wont post it correctly and going straight to IP
ADDRESS/addUser.php?NAME=Ryan
also doesnt work. It auto increments the ID as it should but the name field is always blank.
<?php
//Connect
$sql_connect = mysql_connect("IP", "USER", "PASS") or die ("no DB Connection");
//Select Database
mysql_select_db("practiceCrim") or die ("DB not found");
//Post Info To Var
$name = $_POST['NAME'];
//Query
$query = "INSERT INTO Users (Name)
VALUES ('$name')";
//Run The Query, Get Result
$result = mysql_query( $query, $sql_connect );
//Not Really Needed For You
if(!$result)
{
die('Error: ' . mysql_error());
}
//Close The Connection
mysql_close($sql_connect);
?>
It look like you're getting the name field from the PHP $_POST variable. But your example passes the name field as a GET parameter.
To fix this, you have two options. If you only want to allow name to be passed as a GET parameter, then you need to do this:
$name = $_GET["NAME"];
If you want to allow name to be passed as either a GET or a POST parameter, you can do this:
$name = $_REQUEST["NAME"];
you should replace $name = $_POST['NAME'] with $name = $_GET['NAME'] or $name = $_REQUEST['NAME']
where $_REQUEST is default but don't use $_REQUEST

Ajax + PHP Collaboration Error

NOTE: UPDATE - Please Read
Please Read, updated code, much better:
Also, I added an ajax error function and it doesn't call an error, the first time I do it, but the next time it happens, an error occurs, and the third and fourth times, and so on.
I have some code that doesn't seem to be working, and the problem is probably located in the Ajax request or the PHP receiving function, and I don't know what the problem could be.
Here is the important code, ask for any other code that could also be of help to you.
Jquery Ajax request
$(document).ready(function()
{
$("#secretcoin").mouseover(function()
{
$.ajax(
{
type: "POST",
url: "achievements.php",
data: { Home_Coin_Locator: "Yes" },
error: errorAlert
});
});
});
Receiving side, PHP, which takes this info and stores it in a database:
$achieve4 = $_POST["Home_Coin_Locator"];
$astrSQL = "SELECT * FROM Awards_Inv WHERE Username = '$username'";
$rs3 = mysql_query($astrSQL, $connection);
if ($achieve4 == "Yes")
{
while($row3 = mysql_fetch_array($rs3)){
$soar4 = $row3["Home_Coin_Locator"];
if ($soar4 == "Yes")
{
$soa4 = "Yes";
}
else
{
$soa4 = "No";
$awardSTRsql = "UPDATE Awards_Inv SET 'Home_Coin_Locator' = 'Yes' WHERE Username = '$username'";
mysql_query($awardSTRsql, $connection) or die(mysql_error());
$updatestatsSTRsql = "UPDATE User_Info SET `Coins` = Coins + 120, `Skill Points` = Skill Points + 10, `Awards` = Awards + 1 WHERE Username = '$username'";
mysql_query($updatestatsSTRsql, $connection) or die(mysql_error());
}
}
}
else
{
}
Ok, so my code might be weird, but just try to read it and see what the problem is.
I guess any other advice is also accepted, thanks for looking, and I hope you find something!
I added an error callback function and combined 3 mysql queries into 1, but the problem still exists.
Finally, read this code for info about the $connection and $username variables
$connection = mysql_connect("mysql1.000webhost.com", "username hidden", "password hidden") or die (mysql_error ());
mysql_select_db("a7347456_usersdb") or die(mysql_error());
session_start();
$username = $_SESSION["Username"];
Another factoid:
The error is that the info does not get updated to database, as far as I know.
first thing, make sure that you required the config file witch identify the $connection variable. and it will be easier if you describe what the problem exactly is.

resetting variables in php to display in javascript

I'm trying to get some values off a DB and then putting those values into javascript variables. I managed to do just that, the problem I'm having is when the values in the DB change the values of the variables don't. I figured the problem lies within my PHP, but I cant find it. Can you guys help me?
here's my code:
PHP
<?php
session_start();
if(!isset($_SESSION['u_name'])){
$_SESSION['u_name'] = '';
}
mysql_connect ("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db('raffleiz_Main')or die ("cannot select DB :(");
$signups = mysql_query("SELECT * FROM `Rafflez_info`") or die ('Error: ' . mysql_error());
$row = mysql_num_rows($signups);
//pull all of the data and store it
for($p = 0; $p < $row; $p++){
$participants[$p] = mysql_result($signups, $p, "#_participants");
};
for($a = 0; $a < $row; $a++){
$max_participants[$a] = mysql_result($signups, $a, "max_participants");
};
?>
and my javascript function:
function progress(){
var signups = "<?php echo $participants[0]; ?>";
var maxP = "<?php echo $max_participants[0]; ?>";
alert (signups);
alert (maxP);
var pSignup = signups / maxP;
alert (pSignup);
var total = 550 * pSignup;
var theImg = document.getElementById('progress');
theImg.width = total;
alert (total);
};
I put the "alert" command there so that I could see the change in the values. right now the values don't change no matter what I change them to in the DB.
PHP is a server-side language, meaning that when it served the script from the server to the client, there is no going back.
JavaScript is a client-side language, thus can receive values from a server-side language such as PHP. The values received are then client-side only, a copy if you will.
You can use the XMLHttpRequest API to request a script from a server, updating the local client-side values.
I recommend using the jQuery $.ajax function to easily achieve that.
Here's a nice tutorial from Nettuts to get your started.
You need to call your php page and ask it if values are changes. You can easily use jQuery AJAX to achieve that. Use JSON for easier data transfer. If you want to check if values are changes every 3 seconds for example you can do this:
var interval = window.setInterval(function(){
jQuery.ajax({
url: 'your php file address',
success: function(data){
progress(data)
}
});
}, 3000);
You will need to change you proccess and php code. This is just to give you the idea.

Categories