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>';
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>";
?>
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I'm attempting to extract lat/long points from MySQL to eventually plot them in Leaflet using Javascript. I ran the following PHP code (planelatlong.php) and got an error:
Parse error: syntax error, unexpected 'var' (T_VAR) on line 24.
I looked at similar errors on Stack Overflow for T_VAR, but couldn't find a clear solution for my issue.
Code:
<?php
$username = "stackoverflow";
$password = "thanksstackoverflow";
$host = "localhost";
$database="homedb";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
echo "Connected successfully";
$myquery = "SELECT 'lat', 'lon' FROM 'test01';
$query = mysql_query($myquery);
if (!$query) {
echo mysql_error();
die;
}
$data = array();
echo "var planelatlong = [";
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
echo "[",$data[$x]['lat'],",",$data[$x]['lon'],"]";
if ($x <= (mysql_num_rows($query)-2) ) {
echo ",";
}
}
echo "];";
mysql_close($server);
?>
I think you forgot to end double quote at line 13. Use below line
$myquery = "SELECT 'lat', 'lon' FROM 'test01'";
First time posting here so be kind!
For some reason when my php script reaches the
if ($beds == 'nopref')
the only way I can get the message to display is with echo $message.
The following line with javascript won't display it like my other pages.
Any ideas?
CODE:
<?php
$beds = $_POST['beds'];
$orientation = $_POST['orientation'];
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$conn = mysqli_connect("localhost", "user", "password", "name");
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
if ($beds == 'nopref')
{
$message = "Please select how many beds you'd like";
echo $message;
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
You have broken text because of ' in you'd. Try this:
$message = htmlspecialchars("Please select how many beds you'd like", ENT_QUOTES);
You can escape a ' in JavaScript like \'
if ($beds == 'nopref')
{
$message = "Please select how many beds you\'d like";
echo $message;
echo '<script>alert("'.$message.'");</script>';
}
try this
print "<script type='text/javascript'>window.alert('$message');</script>";
or
print "<script type='text/javascript'>window.alert('Please select how many beds you had like');</script>";
Try this code:
<?php
$message=htmlspecialchars("Hello World's",ENT_QUOTES);
echo "<script>alert('$message')</script>";
?>
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>
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")