Sign in to follow this  
Followers 0
Spunky

Using AngularJS/PHP, getting SQL error

11 posts in this topic

So I am posting this issue in this part of the forum due to the SQL error that I am getting, so my best guess is there is an error in my SQL.

 

Basically, what I am doing is using angularjs's $https to communicate with a PHP file. Here is that code:

$http.post('enterTask.php', task).then(
  function(response){
    alert(response.data);
    $scope.tasks.push(task);
  }
);

So, I am sending some data which works fine. Where I am getting the error was when I decided I want to receive back data as well and I am using the alert to test the response.

 

Here is the PHP code:

<?php
$description = $data->desc;
$reminder = $data->reminder;
$todayDate = $data->todayDate;
$status = $data->status;
require 'databaseConnect.php';
$query="INSERT INTO TaskTracker (DATESTAMP,STATUS,DESCRIPTION,REMINDER) VALUES ('$todayDate','$status','$description','$reminder')";
mysql_query($query) or die(mysql_error());
$query="SELECT ID FROM TaskTracker WHERE DESCRIPTION = $description";
$result = @mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)){
$returnData = $row["ID"];
}
}
mysql_close($db_link);
echo $returnData;
?>

Again, most of this code works just fine, the issue came in when I added everything from the 2nd query and beyond.

 

Here is the error that I am getting when the AJAX runs:

You have an error in your SQL syntax: check the manual that corresponds to your MySQL server version for the right syntax to use near 'a 7th test for good luck' at line 1

Part of the data I am sending is here is a 7th test for good luck. And this is stored in $description. Every time this error pops up, it cuts off the first part of it, which I imagine is some clue as to where the error is in the SQL.

 

Any idea?

 

PS: Sorry the PHP code is sloppy, for some reason it appears blank when I post with it in the code box..

Edited by Spunky

Share this post


Link to post
Share on other sites

Your code is not protected from SQL injection. The code will break if there's an apostrophe in any of the strings. The MySQL library is deprecated due to being insecure and the issue you're experiencing right now is the reason why. Use MySQLi or PDO and use prepared statements: http://www.w3schools.com/php/php_mysql_prepared_statements.asp

 

Where did you get this PHP code? It looks like it came from 10 years ago.

Share this post


Link to post
Share on other sites

I am unable to connect to my server when I convert the code to MySQLi and I have not been able to figure out why. But I am not too concerned, I only work on small, personal projects.

 

I already discovered what happens when I add an apostrophe to the string which is it doesn't add the item to the database. So I am unsure how that is what is happening here. The code works, it's just now that I am trying to receive $returnData I am getting the error, however the data is still being added to the database.

 

My code was created with the help of w3schools, maybe about 10 years ago, yes. But no need to insult the code, it works, let's focus on the code that isn't working, please. :)

Share this post


Link to post
Share on other sites

The solution to your issue with apostrophes is to use prepared statements, which the old mysql library does not support.

 

As for the reason you can't get $returnData, the value in your SELECT query is not delimited, so there's a syntax error.

"SELECT ID FROM TaskTracker WHERE DESCRIPTION = '$description'"

 

This solution will get your code working for some cases, rather than none of them, but to get it working for strings with apostrophes in them you will need to use prepared statements.

Share this post


Link to post
Share on other sites

But no need to insult the code, it works, let's focus on the code that isn't working, please.

No, it doesn't work. Just because you've seen it work most of the time doesn't mean "it works", it just means you usually don't see it break. There are situations where it will never work, for example. If there's a situation where the code never works, even if you only ever run into that situation a small percentage of the time, then the code doesn't work, it's just waiting to break again. This is one of the reasons why PHP has had a bad reputation, because people produce code that usually works, but doesn't work in specific cases, and they don't know why and don't bother to fix it and do things the right way just because they think it works most of the time. It either works or it doesn't, and if it only works "most of the time" instead of "all of the time" then it doesn't work right. Using prepared statements would fix your problem, PHP has supported prepared statements since 2004, but most of the PHP code you see in tutorials still doesn't use them because people think there's nothing wrong since the code works "most of the time" and they don't want to learn the more complex syntax of prepared statements because the other way is easy, even though it's going to break eventually.

 

So, if you want to write the kind of code that people were writing 12 years ago, then you're on the right track (except you're still not using the basic protections that people were using 12 years ago), but you should be aware that your code will not run at all in PHP 7 because you are using things that have been removed from the language because they have been replaced so long ago. It's really up to you whether you want to learn things that you're going to continue to be able to use, or whether you only want to write code that works on a smaller set of PHP servers and will work most of the time, as long as you don't type certain characters into the form.

 

I already discovered what happens when I add an apostrophe to the string which is it doesn't add the item to the database. So I am unsure how that is what is happening here.

It's literally the exact same problem with the exact same solution, so you can either decide that you want to learn the correct way to do this and bring your code up to modern standards so that it will run in the current version of PHP, or you can put a band-aid on that one line of code and wait until it breaks again.

 

I'm not trying to be hard on you, but it's very frustrating to see people post on forums all the time with very old code using very bad practices and they say something like "I just want to get this working" instead of wanting to learn how to do it the right way. You're not the only one with that attitude, it happens all the time and it's frustrating to see because it sounds like people don't want to learn anything, they just want to keep putting patches on the same broken stuff that's going to stay broken.

Share this post


Link to post
Share on other sites

http://stackoverflow.com/questions/30363045/running-php5-access-denied-to-mysqli-connection-but-success-for-mysql

Can't say I haven't tried.

 

Maybe you guys would like to take a crack at it then? Because they couldn't help.

 

So let's stay focused on the important part:

<?php
	$servername = "localhost";
	$username = "username_user";
	$password = "password";
	$dbname = "username_TableName";
	
	$db_con = new mysqli($servername,$username,$password,$dbname);
	
	if($db_con->connect_error){
		die("Connection failed: " . $db_con->connect_error);
	}
?>

The server specific information matches up exactly. All I did was convert it to MySQLi.

 

The error I get:

 

www.mysite.com says:

 

 

 

 

 

Access denied for user 'username'@localhost (using password: NO)

 

(yes, there is a strangely large gap between the top text and bottom which is right above the OK button.)

 

 

Any help?

Share this post


Link to post
Share on other sites

It says you're not using a password, so $password must be empty.

 

Put var_dump() right before the connection to see if the variables have the value you expected them to.

var_dump($servername, $username, $password, $dbname);
$db_con = new mysqli($servername,$username,$password,$dbname);

Share this post


Link to post
Share on other sites

They do, says string(#) "content" for each one.

 

Plus the error is showing twice in the same alert box, not sure if that means anything or helps any.

 

 

How, from my above code, could the $password be empty anyway???

 

Just to cover my bases from pointing fingers I have also tried:

<?php
	$servername = "localhost";
	$username = "username_user";
	$password = "password";
	$dbname = "username_TableName";

	var_dump($servername, $username, $password, $dbname);
	$db_con = new mysqli('localhost','username_user','password','username_TableName');
	
	if($db_con->connect_error){
		die("Connection failed: " . $db_con->connect_error);
	}



?>

(also I realize that where I have TableName is actually database name, I accidentally misinterpreted it as TableName, just don't want to correct it now for consistency)

 

 

I did just notice, however, that data that I am entering to that the PHP is entering into the database with that connection is actually successfully being added. Hmm... thoughts?

 

Also, I should point out that I am actually connecting to the database as soon as my page loads, before I try to enter data via my form which is actually where I am receiving my error. But I am not getting an SQL error when the page loads, just an AngularJS error which is what I am using with AJAX to communicate.

 

here is the PHP that runs from the start:

<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");


require 'databaseConnect.php';

	$query='SELECT * FROM TaskTracker';

	$db_con->query($query);

	$outp = "";

	$result = $db_con->query($query);

	if ($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {
				if($outp != ""){$outp .= ",";}
				$outp .= '{"desc":"' . $row["DESCRIPTION"] . '",';
				$outp .= '"id":"' . $row["ID"] . '",';
				$outp .= '"status":"' . $row["STATUS"] . '",';
				$outp .= '"reminder":"' . $row["REMINDER"] . '",';
				$outp .= '"todayDate":"' . $row["DATESTAMP"] . '"}';
			}
			$outp='{"tasks":['.$outp.']}';
		}

		$result->free();

$db_con->close();

echo($outp);

?>

The error I am getting is:

angular.js:13920 SyntaxError: Unexpected token s in JSON at position 0

 

Why it is suddenly having an issue with my JSON I do not know. I removed the headers though and that error went away.

 

No error, but data is no longer being fetched from the database to my html page.

 

Here's the AngularJS:

$http.get("retrieveData.php").then(function(response){
    $scope.tasks = response.data.tasks;
})

I've done what I can to convert my code to MySQLi, but I may be missing certain things.

Edited by Spunky

Share this post


Link to post
Share on other sites

You should test your PHP without AJAX first, or at least check the developer console to see exactly what's being returned in the AJAX request.

Share this post


Link to post
Share on other sites

I would suggest using PDO instead of mysqli:

 

try{
  $conn = new PDO("mysql:host=localhost;dbname=dbname", "dbuser", "dbpass");
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
  echo 'ERROR: ' . $e->getMessage();
}

Share this post


Link to post
Share on other sites

I would suggest using PDO instead of mysqli:

 

try{
  $conn = new PDO("mysql:host=localhost;dbname=dbname", "dbuser", "dbpass");
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
  echo 'ERROR: ' . $e->getMessage();
}

 

I prefer MySQLi so I will stick with that, thanks. Easier for me to comprehend as I am not a full fledged programmer. I know all about PDO being more versatile.

 

 

You should test your PHP without AJAX first, or at least check the developer console to see exactly what's being returned in the AJAX request.

 

 

 

 

Sure, ofcourse, my bad, I forget that I can easily run the PHP pages alone without the AJAX triggering it.

 

So, the database connection is working. I ran retrieveData.php by itself and the echo $outp is outputting the data from my database as expected, into a JSON object.

 

The issue now seems to lie solely with the AngularJS now so I'll end this topic as is and move onto a different forum area after I have played with this some more.

 

Thanks for all of your helps. I am glad I finally have a working MySQLi connection to use here,for future projects, and to update older projects.

 

 

You should test your PHP without AJAX first, or at least check the developer console to see exactly what's being returned in the AJAX request.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0