I have a little query, which is displaying a text if the server query_string exits in the database.
It works with all sorts of text an figures in mysql, instead of email adresses.
For example if the url looks like "example.com/query.php?test" it works.
If there is an email like "example.com/query.php?test#gmail.com" it doesn't work.
My DB table type is varchar(100).
Any idea?
<?php
$subscriber_email = ($_SERVER['QUERY_STRING']);
mysql_connect("server", "user", "pswd") or die (mysql_error ());
mysql_select_db("newsletter") or die(mysql_error());
$sql = "SELECT * FROM `newsletter submit` WHERE ID='test#gmail.com'";
$query = mysql_query($sql);
echo mysql_error();
echo (mysql_num_rows($query) == 0) ? 'NO' : 'YES';
?>
You should escape your inputs :
$subscriber_email = mysql_escape_string($_SERVER['QUERY_STRING']);
Using a non escaped string causes an error that prevents your query to be executed.
Additionally, you should consider using mysqli, mysql functions being deprecated.
UPDATE : I was a bit too fast and forgot to mention, you should put quotes on each side of your parameter :
$sql = "SELECT * FROM `newsletter submit` WHERE ID='$subscriber_email'";
Use parse_url() like below
$url = 'example.com/query.php?test#gmail.com';
$parm = parse_url($url);
echo $parm['query'];
Related
I know this has been asked before but I cant seem to fix my code.
What I need is to run some php code to query mysql using mysqli for a select statement to retrieve my bcrypt hashed pass so I can compare the user input with the user hashed password. NOTE: I have not yet added mysql_real_escape_string to my $POST variables.
I've changed this code a thousand times still cant get it.
Ive even copy and pasted to a new file a simple query script using num_row
and printf($row['pass']); used echo etc..... I've used fetch array ive tried almost everything I've been all via php mysql at php.net w3c.com etc etc is my system broke? Does mysqli have a bug ? and no i dont want to switch to PDO I wont stop til this is fixed and when there is no longer sql injection vulns
Heres my code:
<?php
$conn = new mysqli('localhost', 'root', '', 'social');
if (mysqli_connect_errno())
{
exit("connection failed" . mysqli_connect_error());
}
else
{
echo "connection established";
}
$db=mysqli_select_db( $conn,'social');
if ($_POST && isset($_POST['submit'], $_POST['password'], $_POST['email']))
{
$pass = ($_POST["password"]);
$email =($_POST["email"]);
$bcrypt = password_hash($pass, PASSWORD_BCRYPT, array('cost' => 12));
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
echo $fetcher;
if ($conn->query($fetcher) === TRUE)
{
echo "query has gone through now we need to store the hash<br /> for comparison";
}
else
{
echo "error did not retrieve hash info";
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
Before you can fetch records from the result of the query, you need to actually perform the query. Your code should be
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$result = $conn->query($query); // This is where the query is executed
$fetcher = $result->fetch_assoc();
Two more points.
First, you don't need to call mysqli_select_db; you've already selected the database in your constructor call, so you only need to call mysqli_select_db if you want to access a different database.
Second, instead of calling mysql_real_escape_string you should look into using prepared statements, which do the same thing and also correctly handle type-matching and quoting.
Try fetching the value from database after executing the query
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$executedQuery = $conn->query($query);
if($executedQuery) {
$fetcher = mysqli_fetch_assoc($executedQuery);
echo "query has gone through ---------";
} else {
echo "error did not retrieve hash info";
}
$query = "SELECT pass FROM social WHERE id = 11"; // took the (``) out of the query and added this im assuming the value is stored in the $row variable and I may be able to use $row with the user input to verify hash via bcrypt!!!
$result = $conn->query($query);
while($row = mysqli_fetch_array($result))
{
echo $row['pass'];
echo "<br />";
}
I'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.
$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?
This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.
<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];
$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");
if(mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
$mysqli->close();
?>
It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.
Connecting to a database using the MySQLi API requires 4 parameters:
http://php.net/manual/en/function.mysqli-connect.php
If your password isn't required, you still need an (empty) parameter for it.
I.e.: $mysqli = new mysqli("host","user", "", "db");
Plus, as noted.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Footnotes:
As stated in the original post. Strings require to be quoted in values.
You need to add quotes to the strings in your query:
$query = "SELECT *
FROM characters
WHERE username='".$username."' and charactername='".$characterName."'";
i have tried this code to insert value into database, but i don't Know why, the value was not send into the databases. The table i have created in the mysql :
<?php
require_once "connection.php";
$conn = connect();
$db = connectdb();
mysql_select_db($db,$conn) or die (mysql_error() . "\n");
$query_usr = "select * from soalselidik";
$usr = mysql_query($query_usr,$conn) or die(mysql_error()."\n".$query_usr);
$row_usr=mysql_fetch_assoc($usr);
//to insert in database
$a1=$_POST['a1'];
$a2=$_POST['a2'];
$a3=$_POST['a3'];
$a4=$_POST['a4'];
$b1=$_POST['b1'];
$b2=$_POST['b2'];
$b3=$_POST['b3'];
$b4=$_POST['b4'];
$c1=$_POST['c1'];
$c2=$_POST['c2'];
$c3=$_POST['c3'];
$c4=$_POST['c4'];
$d1=$_POST['d1'];
$d2=$_POST['d2'];
$d3=$_POST['d3'];
$d4=$_POST['d4'];
$e1=$_POST['e1'];
$f1=$_POST['f1'];
echo $query ="insert into soalselidik (a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,d1,d2,d3,d4,e1,f1) values('$a1','$a2','$a3','$a4','$b1','$b2','$b3','$b4','$c1','$c2','$c3','$c4''$d1','$d2','$d3','$d4','$e1','$f1')";
$result = mysql_query($query);
echo "<script languange = 'Javascript'>
alert('thankyou ! Penilaian anda diterima ');
location.href = 'home.php';</script>";
?>
'$c4''$d1'
Find that in your query and fix it :) And please do some error checking, and please stop using MySQL_* for your own good. Why should people not run any error checking mechanism that's already provided in the language and expect others to debug typos?
In case you didn't get it, there's a comma missing
How can I prevent SQL injection in PHP?
I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.
For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!