Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Sign in to follow this  
Spunky

Using AngularJS/PHP, getting SQL error

Recommended Posts

Spunky    0

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
Ingolme    798

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
Spunky    0

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
Ingolme    798

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
justsomeguy    954

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
Spunky    0

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
Ingolme    798

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
Spunky    0

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
Ingolme    798

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
justsomeguy    954

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
Spunky    0

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  

×