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")
Related
getReport.php
<?php
$data = $_POST;
//print_r($_POST);
if (isset($_POST['idws']))
{
$getListData = new getListData();
$List = $getListData->get($_POST['idws']);
print_r($List);
}
else{
exit;
}
class getListData {
public function get($idws){
include __DIR__ .'/../../../include/conn.php';
$q = "SELECT * from customers where idws= '$idws'
ORDER BY idws DESC";
$stmt = mysql_query($q);
$id = array();
$outp = '';
while($row = mysql_fetch_array($stmt)){
if ($outp != "") {$outp .= ",";}
$outp .= '{"item_d":"'.rawurlencode($row['item_desc']).'",';
$outp .= '"qty":"'. rawurlencode($row["qty"]). '"}';
}
$result = '{ "status":"ok", "message":"1", "records":['.$outp.']}';
return $result;
}
}
?>
I'm using a HTML tag inside PHP with onclick, and I am confused when I get the end of input error.
echo "<td><div style='cursor:pointer; color:#3386FF' data-toggle='modal' data-target='.detmatstat' onclick='getReport("."'".$data['id']."'".")'>$data[id]</div></td>";
I guess it is because the parentheses inside the getReport. So I tried to switch the quotation mark position, from this:
onclick='getReport("."'".$data['id']."'".")'
to this:
onclick='getReport(".'"'.$data['id'].'"'.")'
But I get this Error:
Uncaught ReferenceError: getReport is not defined
at HTMLDivElement.onclick
Honestly, I'm still confused how to read the correct tag with so many quotation mark. Please help me fix this.
You could do this :
<?php echo "<div style='cursor:pointer; color:#3386FF' data-toggle='modal' data-target='.detmatstat' onclick='getReport(".$data[id].")'>".$data[id]."</div>";
?>
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.
I have connected and pull retrieve some data using PHP but I would like to know:
It is PHP or Javascrip , JS better to interacts with Postgresql
It is an easy way to do the same as my PHP code in Javascrip or JS? if so, how?
In my example: I'm inserting the name, last name and email and retrieving the country.
Thank you very much
<!DOCTYPE HTML>
<html>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = $AddressErr = "";
$name = $email = $surname = $address = "";
<select name="countryselect" id="countryselect">
<?php
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>
</select>
<input type="submit" name="submit" value="SAVE">
</form>
<?php
if ($nameErr == '' && $emailErr == '' && $surnameErr == '')
{
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$firstname = pg_escape_string($_POST['name']);
$surname = pg_escape_string($_POST['surname']);
$emailaddress = pg_escape_string($_POST['email']);
$query = "INSERT INTO host(firstname, surname, emailaddress) VALUES('" . $firstname . "', '" . $surname . "', '" . $emailaddress . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
//printf ("These values were inserted into the database - %s %s %s", $firstname, $surname, $emailaddress);
pg_close();
}
?>
</body>
</html>
what is the error in this statement
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$database = "mcndb";
$cons = mysqli_connect($host, $uname, $pass, $database);
mysqli_select_db($cons, $database);
if (!$cons) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['username'])) {
date_default_timezone_set("Asia/Bangkok");
$today = date("Y/m/d h:i:s:A");
$username = mysqli_real_escape_string($cons, $_POST['username']);
$password = mysqli_real_escape_string($cons, $_POST['password']);
$firstname = mysqli_real_escape_string($cons, $_POST['firstname']);
$middlename = mysqli_real_escape_string($cons, $_POST['middlename']);
$lastname = mysqli_real_escape_string($cons, $_POST['lastname']);
// $age=mysqli_real_escape_string($cons,$_POST['age']);
$gender = mysqli_real_escape_string($cons, $_POST['gender']);
$email = mysqli_real_escape_string($cons, $_POST['usremail']);
$companyname = mysqli_real_escape_string($cons, $_POST['companyname']);
$position = mysqli_real_escape_string($cons, $_POST['position']);
$contactnumber = mysqli_real_escape_string($cons, $_POST['contactnumber']);
$addresss = mysqli_real_escape_string($cons, $_POST['address']);
$sql = "INSERT INTO tbltry (username,password,email,firstname,middlename,lastname,gender, company_name,position,contact_number,address_of_company,dateofregister)
VALUES ('$username', '$password', '$email','$firstname', '$middlename','$lastname','$gender', '$companyname','$position','$contactnumber','$addresss','$today')";
if ($cons->query($sql) == TRUE) {
echo '<script>';
echo 'alert("Successfully created an account")';
echo '</script>';
} else {
echo '<script>';
echo "Error: " . $sql . "<br>" . $cons->error;
echo 'alert("Account already exist")';
echo '</script>';
}
}
?>
enter image description here
the problem with this is that when ever i try registering a dulicate value to unique column in databse, the error message in the alert dont show up and it does not show any kind of error even in sql it just says Uncaught SyntaxError: Unexpected identifier so what is wrong with my code that the alert for error dont show?
so what is wrong with my code
This:
<script>
Error: some text<br>some more text
alert("Account already exist")
</script>
(And potentially other things, but this seems to be where the error you're currently seeing takes place.)
That first line of JavaScript code isn't actually JavaScript code. It's just text. So Error: (and everything after it) is an unexpected identifier as far as JavaScript is concerned.
I suspect you meant to put that text outside of the script block:
echo "Error: " . $sql . "<br>" . $cons->error;
echo '<script>';
echo 'alert("Account already exist")';
echo '</script>';
i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter