I'm attempting to connect to an api and get a user from a donation system and then open a socket to a game to automatically give a user the amount they donated for. I need to get rid of this error:
"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 '$r' at line 1"
I can't seem to see what the problem is? Here's the script:
<?php
$tablename="CENSORED";
$DBUSER="CENSORED";
$DBPASSWORD="CENSORED";
$DBHOST="CENSORED";
?>
<?php
$urlMask = 'CENSORED';
$getUser = function($id) use ($urlMask) {
list($user) = json_decode(file_get_contents(sprintf($urlMask, $id)));
return (object) $user;
};
$user = $getUser(4087396);
$Username = $user->user->username;
$Rank = $user->item_name;
$IGN = $user->custom_field;
echo '<center> Your username is '.$IGN.' correct? </center> ';
?>
<?php
if(isset($_POST['Clickbutton'])){
$con = mysql_connect($DBHOST,$DBUSER,$DBPASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($tablename, $con);
$sql="SELECT IGN FROM fisktable WHERE IGN='$IGN' and Rank='$Rank'" ;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
}
$result = mysql_query('$r') or die(mysql_error());
if(mysql_num_rows($result) == 1) {
echo 'That username has already been given their rank!';
} else {
$HOST = "77.45----"; //the ip of the bukkit server
$password = "chdfxfdxh";
//Can't touch this:
$sock = socket_create(AF_INET, SOCK_STREAM, 0)
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, 4445)
or die("error: could not connect to host\n");
//Authentification
socket_write($sock, $command = md5($password)."<Password>", strlen($command) + 1)
or die("error: failed to write to socket\n");
//Begin custom code here.
socket_write($sock, $command = "/Command/ExecuteConsoleCommand:pex user ($IGN) group set ($Rank);", strlen($command) + 1) //Writing text/command we want to send to the server
or die("error: failed to write to socket\n");
socket_write($sock, $command = "Thanks, ($IGN) for donating to the ($Rank) rank! ;", strlen($command) + 1)
or die("error: failed to write to socket\n");
mysql_select_db($tablename, $con);
$sql="INSERT INTO $tablename(IGN,Rank) VALUES ('$IGN','$Rank')" ;
exit();
}}
?>
<center>
<form method="POST">
<input name="Clickbutton" type="submit" value="Yes! I would like to receive my rank!"/>
</form>
</center>
I'm trying to check if the user has been already given their rank and items by adding them to a database when their given their items. And then if they try to do it twice they will get an error saying that they have already been given their rank!
If you see any other problems or potental problems feel free to point them out.
Thanks!
Basic PHP syntax error:
$result = mysql_query('$r') or die(mysql_error());
^--^--- remove the quotes
single quoted strings do not interpolate values. You're passing a literal $ and r to mysql as a query.
Related
I have found record from login table but my mysql query is now executing.
following is my code.
$sqlQuery = "SELECT * FROM ".$table."
WHERE mobile_number='".$mobile_number."' AND
password='".base64_encode($password)."'";
// End
$select = mysql_query($sqlQuery);
$result = mysql_num_rows($select);
echo "<pre>Rest";
print_r($result);
It's always return 0 but same query is working in Phpmyadmin dashboard.
When i used mysql_error() function with mysql_query like following
$select = mysql_query($sqlQuery) or die ('Error updating database: '.mysql_error());
It's given error : Access denied for user ''#'localhost' (using password: NO)
Following is my connection code..
$dbname = "######";
$host = "localhost";
$user = "#####";
$password = "#####";
$connection = mysql_connect($host,$user,$password) or die("Error in database connection.");
if (!$connection)
{
return false;
}
if(!mysql_select_db($dbname, $connection))
{
return false;
}
I don't know why i faced the problem if anyone have idea about this pleas help me on this.
Thank You!!
Guess you gotta connect to your SQL Server with username and password. Error message says you didn’t even pass a username.
Simple example:
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
…
// do your stuff here
Please be sure to – at least – secure your parameters be escaping them with mysql_real_escape_string() for instance:
http://php.net/manual/en/function.mysql-real-escape-string.php
Or, even better, use PDO:
$stmt = $pdo->prepare('SELECT * FROM your_table WHERE mobile_number = :mobile_number');
$stmt->execute(array('mobile_number' => $mobile_number));
…
You should check the host, user name, and password in the configuration file and make sure that the information is consistent with the information given by the MySQL server administrator.
Reset the password and try it out:
Enter set password for 'root'#'localhost'=password(' your password ');Then restart the mysql service.Enter mysql-u root-p
I am trying to start a pgsql connection in php but i get pg_last_error(): No PostgreSQL link opened yet Please forgive my amateur question as i am a bit new to php.
Here is my php code:
<?php
$connect = pg_connect("host=xxx.xx.xxx.21 dbname=d106 user=b16 password=bran") or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
In your pgsql connection you have missed the port number.
Try this way.
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" ) or die("Could not connect: " . pg_last_error());
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo "no results ";
}
while($row = pg_fetch_array($result))
{
$coor = $row['thestartgeom'];
echo $coor;
}
pg_close($connect);
?>
You can store PgSQL connection code in one PHP file to reuse
pgsql_db_connection.php file
<?php
$host = "host=xxx.xx.xxx.21";
$port = "port=5432";
$dbname = "dbname=d106";
$credentials = "user=b16 password=bran";
$connect= pg_connect( "$host $port $dbname $credentials" );
if(!$connect){
echo "Error : Unable to open database\n";
}
?>
Call pgsql_db_connection.php file in other php files to use your database connection.
<?php
require_once('pgsql_db_connection.php');
$result = pg_query($connect,"SELECT distinct thestartgeom FROM bikes");
if (!$result)
{
echo pg_last_error($connect);
exit;
}
while($row = pg_fetch_array($result))
{
$coor = $row[0];
echo $coor;
}
?>
When pg_connect fails, it returns FALSE and produces a PHP warning with the detailed information on why it couldn't initiate the connection. If you can see the other message:pg_last_error(): No PostgreSQL link opened yet that you're reporting, I'd expect you should be able to see the previous one too, which is the one normally telling the reason of the failure.
If the display_errors configuration setting is set to 0, the first message would not show up on the browser/screen but the second would not either.
Anyway, assuming you can't have access to pg_connect warnings for whatever reason such as custom error handler, what's wrong with your code is that pg_last_error() must have an already opened connection to work.
To access the detailed error message from a failed pg_connect, the built-in PHP function error_get_last() (returning an array) could be used.
<?
$connect= pg_connect("your-connect-string");
if (!$connect) {
print_r(error_get_last());
// for only the message:
// echo error_get_last()['message']
}
die("DB connection failed");
?>
See also how to catch pg_connect() function error? if you prefer exceptions.
I made a php script which'll echo an image if the correct password is entered; so that, nobody can access the images stored on my server directly, thus, making my server more secure. Now, for the php script I used GET method to generate a mysql_query to my database in order to check if the email and password entered by the user are associated with a relevant account and then echo the image from a folder on my server. Now, in order to pass the parameters while runtime, I'm adding them in the URL like this:
http://<mywebserver>/get_image.php/?email=<email>&password=<password>&file_name=<image-file-name>
But, something's wrong with this whole setup, and I'm getting the following error:
Warning: mysql_query() [function.mysql-query]: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO) in
/home/uXXXXXXXXX/public_html/get_image.php on line 11
Warning: mysql_query() [function.mysql-query]: A link to the server
could not be established in /home/uXXXXXXXXX/public_html/get_image.php
on line 11 Error getting data: Access denied for user
'uXXXXXXXXX'#'XX.XX.XX.XX' (using password: NO)
Here is my php script, get_image.php:
<?php
$file_path = "/ProfilePics/";
if(isset($_GET['email']) && isset($_GET['password']) && isset($_GET['file_name'])) {
$id = "\"" . $_GET['email'] . "\"";
$typed_password = "\"" . $_GET['password'] . "\"";
$file = $_GET['file_name'];
$result = mysql_query("SELECT * FROM students WHERE email = $id AND password = $typed_password") or die ("Error getting data: " . mysql_error()); //line 11
if(!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$user = array();
$user["email"] = $result["email"];
$user["password"] = $result["password"];
$pass = "\"" . $user["password"] . "\"";
if($pass == $typed_password) {
$img_path = $file_path . $file;
echo '<img src="' . $img_path . '" name = "cover" />';
} else {
echo "Incorrect password";
}
} else {
echo "Unable to find user";
}
} else {
echo "Unable to find user";
}
} else {
echo "Required field(s) is missing";
}
?>
I agree, that there are lots of other questions already on stackoverflow stating similar problems. But, I didn't find the solution(s) to those questions applicable for my code. So, any help on this will be highly appreciated. Thank you for your time!
This is because you have not connected your file get_image.php to your MySQL database. Do so as follows:
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="database"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
Simply replace the information above with the correct information.
You don't seem to be connecting to the database before you try to send queries to it.
It should like something like this:
$conn = new mysqli($servername, $username, $password, $dbname);
Taken from the example here:
http://www.w3schools.com/php/php_mysql_select.asp
Furthermore, if you care, you should consider using PDO or some other method of preventing SQL injection attacks.
SQL Injection:
https://en.wikipedia.org/wiki/SQL_injection
Information on PDO:
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
setup a database connection first:
$con = mysql_connect('server','username','password');
$rst = mysql_query('select...', $con);
remember that kind of library to access mysql is outdated.
imagine someone logging in with this password:
password = '"; DROP TABLE students;'
or something crafted better.
There are different libraries like PDO or MYSQLI that take cares of this for you.
in newer releases of php standard mysql libis deprecated and removed
Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13
Could not connect: Lost connection to MySQL server during query.
Also, line 13 is indicating the line in lib.php:
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.
Lastly, I get the same error from both a localhost and a remote server using mysql
lib.php
<?
//Database Information
$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php
<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']); break;
case "register":
register($_POST['username'], $_POST['password']); break;
}
exit();
?>
api.php
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson('Registration failed');
}
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
?>
As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.
Straight from the manual:
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.
If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).
I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost
I have email.txt stored in my server the path of email.txt is
/home/xxxx/public_htnl/email.txt
email.txt consists of several thousand emails of subscriber which gets updated daily.
I want to import these emails to other database daily using cron.
I have tried this but its giving error
Could not load. Access denied for user 'test'#'localhost' (using password: YES)
I think I don't have permission to run LOAD DATA INFILE
My code is:
<?php
$db = mysql_connect('localhost', 'test', 'test')
or die('Failed to connect');
mysql_select_db('test', $db);
$string = file_get_contents("http://www.xyz.com/email.txt", "r");
$myFile = "/home/xxx/public_html/email.txt";
$fh = fopen($myFile, 'w') or die("Could not open: " . mysql_error());
fwrite($fh, $string);
fclose($fh);
$result = mysql_query("LOAD DATA INFILE '$myFile'" .
" INTO TABLE email");
if (!$result) {
die("Could not load. " . mysql_error());
}
?>
Any other good method can be accepted.please don't advice that store data directly in other database while storing emails etc..
As the root MySQL user, try running the query:
GRANT FILE on *.* to 'test'#'localhost';
If you still get the error, make sure your username and password for the test user are correct and that the host you are accessing MySQL from matches the host for the test user and password.
EDIT:
<?php
$db = mysql_connect('localhost', 'test', 'test') or die(mysql_error());
if (!mysql_select_db('test', $db)) die(mysql_error());
$emails = file("http://www.xyz.com/email.txt");
foreach($emails as $email) {
$email = trim($email);
if ($email == '' || strpos($email, '#') === false) continue;
$email = mysql_real_escape_string($email);
$query = "INSERT INTO `email` VALUES('$email')";
$result = mysql_query($query);
if (!$result) {
echo "Failed to insert $email. " . mysql_error() . "<br />\n";
}
}
If there are many, many emails, you can build an array of email addresses and do an extended insert every so often.
INSERT INTO emails VALUES('email1'), ('email2'), ('email3'), ('email4')