Updating a mysql db with php ajax request - javascript

I have this php code that updates a row in my MySQL database, based on 3 variables sent with ajax but that returns a http 500 error:
<?php
$dbname = 'xxxxxxxxxx';
$dbuser = 'xxxxxxxxxxxx';
$dbpass = 'xxxxxxxxxxxxx';
$dbhost = 'xxxxxxxxx';
$link = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$topparent = $_POST['name'];
$column = $_POST['column'];
$value = $_POST['value'];
$sql = "UPDATE reloaded SET" . $column . " = '" .$value . "'WHERE top_parent = '" . $name ."';
$retval = mysql_query( $sql, $link );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "success\n";
mysql_close($link);
?>
My jquery js is this. The variables get passed correctly (tried with alert):
function updatedb(a,b,c){
$.ajax({
url: "updatedb.php",
type: 'POST',
data: ({name:a,column:b,value:c}),
success: function(msg) {
alert('DB updated');
}
});
};
Any idea why it returns an error? I have spent some time going over the code, trying different variations but can't seem to figure it out.

There is a PHP syntax error in the SQL query statement.
You have missed to end the " and hence the 500 error.
The corrected code:
$sql = "UPDATE reloaded SET " . $column . " = '" .$value . "' WHERE top_parent = '" . $name ."'";
Edit
Adding to that, there is no space after the SET keyword.
Fixing this will update your db properly.

Related

How to fetch data from database and display it using AJAX in an app

I have not touched PHP or AJAX that much in about 8 years, so my memory on this is pretty low at the moment.
What I'm doing is fetching data from my database that works great.
Then I want to use AJAX to get the data from the PHP file.
My PHP file on my server is connecting to the database and fetching the table "Form".
This data is then going to be retrieved by another app trough AJAX.
I have a working PHP file, but how I should order this for the AJAX to fetch it nicely is a big question for me.
The things I have at the moment is:
PHP FILE:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM form";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row['name'];
$country = $row['country'];
$email = $row['email'];
$need = $row['need'];
$available = $row['available'];
echo "name: " . $name . "<br> Country: " . $country . " <br> Email: " . $email . "<br> Need: " . $need . "<br> Available: " . $available;
$form_data = array();
array_push($form_data)
}
} else {
echo "Null results";
}
$conn->close();
?>
AJAX FILE:
$.ajax({
url: 'url',
data: "",
dataType: 'json',
success: function(data) {
}
});
The AJAX file is not complete since I'm still wondering about these PHP results.
Right now they are just stored in variables.
What is the best way to store these results to get an fetch for AJAX here?
Should I put the results in an array and then push that array into another array?
There can be many lines in forms, and I want 1 person with data: name, country etc to be in one array. Or is it stupid to have it in an array?
I hope someone can give a little clue and help me on my way here. Long time since I have been doing PHP and a little bit unclear about the best approach here.
Been searching for a while, but nothing made so much sense to me, so I'm coming here hoping someone can guide the way.
Happy Easter.
Create an array and save all your data, then json_encode to send the data to JavaScript.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_julekgwa";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM form";
$result = $conn->query($sql);
$rows = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row['name'];
$country = $row['country'];
$email = $row['email'];
$need = $row['need'];
$available = $row['available'];
$rows[] = "{ name: " . $name . ", Country: " . $country . ", Email: " . $email . ", Need: " . $need . ", Available: " . $available . "}";
}
echo json_encode($rows);
} else {
echo json_encode([ "error" => "Null results"]);
}
$conn->close();
?>
In your ajax do the following
$.ajax({
url: 'file.php',
type: "GET",
dataType: 'json',
success: function(data) {
data.forEach(item => {
console.log(item);
});
},
error: function(data) {
console.log(data);
}
});

PHP does not receive complete data when send it by AJAX

So I'm building a mobile (cordova) app using a mySQL server, PHP, javascript (jQuery) but I have encountered a rather annoying problem.
When sending a test string with AJAX the recieving end, a PHP script does not receive all the data:
function testJson() {
$.ajax({
type: 'POST',
data: {
text: "hello, this is a test to see if the string is send."
},
url: 'http://a.working.url/save.php',
success: function(data) {
alert('succes');
},
error: function(data) {
alert('There was an error adding your comment');
}
});
return false;
}
then at the serverside I have a small PHP script:
<?php
$server = "localhost:3307";
//changed port to 3307
$username = "user";
$password = "pass";
$database = "test";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$comment = $_POST['text'];
echo $comment;
$sql = "INSERT INTO data (comment) ";
$sql .= "VALUES ('$comment')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
but this PHP script did not recieve the full string, when I check using:
echo $_POST['text']
It only got: "hello, this is a test to see if the" (without quotes).
If anybody can help me it would be great cause I cannot continue working on the app unless the data transfer works.
Thanks in advance.

How to create a table in database using jquery

I have a button that when pressed will create a table in the database.
I tried this
index.html
<button id="loadButton" type="button" class="btn btn-success" style="margin-top:5px;">Carregar Base de Dados</button>
dash.js
$('#loadButton').click(function() {
$.ajax({
url: 'connectdb.php'
});
});
connectdb.php
<?php
$server = 'localhost';
$user = 'root';
$password = '*****';
$database = 'test';
$con = mysql_connect($server, $user, $password, $database);
if (!$con) {
die('error: ' . mysql_error($con));
}
// Create table
$sql="CREATE TABLE Post(
id_post int Primary Key,
titulo varchar(100) not null,
imagem longblob,
descricao varchar(1000) not null,
hashtag varchar(100) not null
)";
// Execute query
mysql_query($con,$sql))
?>
?>
but when I check my database table was not created.
I'm new in jquery, what I'm doing wrong. can someone help me?
Try this and if you want to be shure the php code is called replace all the code with an simple echo and check the response.
$server = 'localhost';
$user = 'root';
$password = '*****';
$database = 'test';
$db = new mysqli($server, $user, $password, $database);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$db->query("
CREATE TABLE Post(
id_post int Primary Key,
titulo varchar(100) not null,
imagem longblob,
descricao varchar(1000) not null,
hashtag varchar(100) not null
)");
First : Please use MySQLi* mysql_* is deprecated.
You have errors in your .php code
mysql_query($con,$sql))
one ) of )) to much
you should have a ; at the end of your command
wrong order $con,$sql
this is OK
mysql_query($sql,$con);
sometimes you should use the database here 'test' in your query
$database = 'test';
...
$sql="CREATE TABLE test.Post(
you should test your result
$result = mysql_query($sql,$con);
if (!$result) {
$message = 'invalid query: ' . mysql_error() . "\n";
$message .= 'your query: ' . $sql;
echo $message;
die($message);
}
To search for errors this is very helpful !
go to connectdb.php directly e.g. http://www.example.com/connectdb.php, fix all the errors and make sure it is working first.

Retrieving data from PHP using AJAX to send to different PHP file

Ok so I have:
A PHP file that queries a database and displays the results of the query,
a HTML file that displays the results using AJAX and
another PHP file that I need to send the data from the first PHP file to.
How can I do this?
My first PHP file displays:
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div class='result'><a id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></a>";
}
So the AJAX brings this in and displays it in the HTML. Is there a way of sending the ID field when the link is clicked so that it can be used in another PHP file to display the data for that specific ID.
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: $("#hiddenid"),
success: function (data) {
$("#individualshop").load("external-data/shop.php");
}
});
So that the data from the #hiddendiv ($row ['ID']) will be sent to the new PHP file. This isn't working.
shop.php has the code:
//get shop ID
$shopid = $_POST['ID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE ID='$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='searchresult'><strong>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div>";
}
But I'm not sure how to retrieve the ID?
Basically I need to be able to click on each search result and have another PHP file bring in specific data associated with the ID of the search result. Any suggestions??
Thanks in advance!
I'm not 100% sure this is what you want but this is one way.
This is your first php file. I've added an onclick listener to it so when a user clicks a row it will fire a JavaScript passing the $row['id'] variable.
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div onclick='someFunction(" . $row['id'] . ")' class='result'><div id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></div>";
}
Then add this script to the header of the page.
<script>
function someFunction(d){
var response = httpGet("http://yourdomain.com/newphpfile.php?page_id=" +d);
document.getElementById('someResultArea').innerHTML = response;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
Then your new php file should do something like this.
newphpfile.php
<?php
session_start();
$page_id = strip_tags($_GET['page_id']);
$processResult = 'handle your result';
echo $processResult;
?>
I hope this helps you out.
Use this;
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: "ID=" + $("#hiddenid"),
success: function (data) {
$("#individualshop").html(data);
}
});
});
Note: Do not forget to return html in shop.php
You can fetch the clicked element id by using either javascript or jquery, and put it in the GET parameters on the php link
the ajax target would be ajax.php?id=test
Then get the value of id via $_GET['id']

how to throw an exception from php to angular $http service

i am working on a blog in angularJS and i use php to generate a json with data from a database.
My angular 'get article' function looks like this
$scope.getDetail = function() {
$http.get('php/blogGetArticle.php?id=2').success(function(json) {
$scope.jsonDetail = json;
alert('ok');
}).error(function() {
alert('error');
});
};
and my php 'blogGetArticle.php' looks like this.
<?php
$id = $_GET['id'];
$dbhost = "localhost";
$dbport = "5432";
$dbname = "pd";
$dbuser = "postgres";
$dbpass = "123";
$connect = pg_connect("host=" . $dbhost . " port=" . $dbport . " dbname=" . $dbname . " user=" . $dbuser . " password=" . $dbpass);
if(!$connect)
die("error 0"); // connect error
$query = "SELECT * FROM blog WHERE id=" . $id;
$result = pg_query($connect, $query);
if(!$result)
die('error 1'); // query error
$row = pg_fetch_row($result);
$json = '{';
$json .= '"id":"' . addslashes($row[0]) . '",';
$json .= '"title":"' . addslashes($row[1]) . '",';
$json .= '"message":"' . addslashes($row[2]) . '",';
$json .= '"category":"' . addslashes($row[4]) . '"';
$json .= '}';
echo $json;
?>
Now what i try to do is i try to make the angular function take to the .error branch when i call something inside php .. i dont know how to explain well. Example when i have in php an id that is lower than 10, i want the angular function to throw an exception but i want to make it from php file to throw that exception to angular function.
Thank you, Daniel!
EDIT: so how do i throw a 4xx or 5xx error ?
PHP:
try {
} catch (Exception $e) {
header("HTTP/1.1 500 Internal Server Error");
echo '{"data": "Exception occurred: '.$e->getMessage().'"}';
}
AngularJS
, function(error) {
$log.error('Error message: '+error.data);
});
You can do like
if(!$connect)
// or may be code 500
header("HTTP/1.0 404 Not Found");
exit;
$query = "SELECT * FROM blog WHERE id=" . $id;
$result = pg_query($connect, $query);
if(!$result)
header("HTTP/1.0 404 Not Found");
exit;
I advice you to try http://us.php.net/manual/en/function.json-encode.php without any further ado :)
Bye
Couldn't you return json with a different format?
if(!$result){
$json = '{';
$json .= '"error":"failed loading data",';
$json .= '}';
}else{
$row = pg_fetch_row($result);
$json = '{';
$json .= '"id":"' . addslashes($row[0]) . '",';
$json .= '"title":"' . addslashes($row[1]) . '",';
$json .= '"message":"' . addslashes($row[2]) . '",';
$json .= '"category":"' . addslashes($row[4]) . '"';
$json .= '}';
}
echo $json;
Then in angular detect if error exists in json and then you can plan for multiple errors vs processes status result calls.
jsonObj.hasOwnProperty("error")

Categories

Resources