This is the code I have, but I get this error when I try to get variable from the url: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
The URL variable DEVID is a long string of characters, numbers, dashes, and underscores. Any ideas on what is wrong?
<?php
$con = mysql_connect("server","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$result = mysql_query("SELECT * FROM $user WHERE DEVID=$DEVID");
while($row = mysql_fetch_array($result))
{
if (($row["FN"]) == NULL){
echo '<meta http-equiv="refresh" content="1;url=../register/default.php?user=';
echo $_GET["user"];
echo '&DEVID=';
echo $_GET["DEVID"];
echo '">Please hold, we are taking you to the registration page.<br/><br/>';
}
}
mysql_close($con);
?>
If $DEVID is a VARCHAR field then you'll need single quotes around it in your SQL query:
SELECT * FROM $user WHERE DEVID='$DEVID'
Where is $DEVID being set before the query? You're not using PHP register_globals, and that's coming from a query-string variable are you? This is 2012! When are people going to stop using that?
Do the variables $user and $DEVID has values? Have they been initialized ?
Assuming that $user and $DEVID has been initailized the error is happening because mysql_query is returning false as the SQL query generates error when executed.
Moreover you should not use variables directly obtained from the URL. Clean the value for possible presence of single qoutes. Use mysql_real_esacape_string(). Replace the mysql_query line with the below to see the SQL error if it occurs.
$DEVID=mysql_real_escape_string($DEVID);
$result = mysql_query("SELECT * FROM $user WHERE DEVID='$DEVID'") or die(mysql_error());
Related
I'm facing a weird problem, I'm trying to implement a simple Usercheck with PHP 7.1.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//checking if nickname already exists
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
//sending query to sql database
$doesExist = mysqli_query($con, $checkUserExistanceSql)
or die ("Fehler in der Datenbankabfrage");
if(mysqli_num_rows($doesExist)>=1){
echo "Nickname not available, use another name";
}
But I'm getting this warning
Warning: A non-numeric value encountered in E:\XAMPP\htdocs... Line 29
Line 29 is the $checkUserExistanceSql. Any ideas where the problem is?
String concatenation on PHP uses . (dot) as operator, not + (plus).
You actual code uses +:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
This is why PHP is telling that $nickname isn't a numeric variable. It cannot sum strings, only concatenate.
Change your operator to . and it will work:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" . $nickname . "'";
You can also use this syntax, with the same result but cleaner code:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='{$nickname}'";
Security Alert
You code is sucessive to SQL injection. You should use prepared statements instead of concatenating your variables into the Query.
Thanks to the help of Yolo and Elias Soares.
The script runs flawless now, I also used prepared statement to counter the risk of sql injection as mentiones by elias.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//prepared statement for sql query
$stmt = $con -> prepare("SELECT nickname FROM user WHERE (nickname=?)");
$stmt -> bind_param("s", $nickname);
$stmt->execute();
//checkking result, if nickname is already used
if($stmt->get_result()){
echo "0";
} else {
//insert user
}
I'm trying to show a value from a database table through PHP echo. The MySQL result is a double (10, 2).
<?php $link = new mysqli('127.0.0.1', '*******', '*******', '*******');
if ($link->connect_errno) {
die('Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$user = $_SESSION['user'];
$result = $link->query("SELECT * FROM users WHERE username='$user' AND active=1");
$numrows = $result->num_rows;
if($numrows == 0 || $numrows > 1)
{
$link->close();
session_destroy();
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=**************">';
exit;
}
else if($numrows == 1)
{
//$sid = $result(8);
echo '<strong>this is my string in which i want to show the result in' . $result(8) . 'rest of the string';}?>
Line where the error is show is the echo line (in the end). Can anyone point me out to what I am doing wrong here? Thank you.
you are calling $result(8) which is a method call in php. I think you meant
$dataRow = $result->fetch_array(MYSQLI_ASSOC);
// collect whatever you need from the array $dataRow array
since PHP is an interpreted language you can do such things as assign a value to a variable and call that variable
$func = 'myFunc';
$func(); // will call the function myFunc
The $result variable is a MySQLi Result. You want to get a row from that result set. To do that, use fetch_assoc. This will give you an associative array with all of the fields of the table as keys.
$row = $result->fetch_assoc();
echo $row['username'];
echo $row['whatever'];
EDIT: It may be valuable to note that you are susceptible to the following security risks: SQL injection, cross-site scripting, and Cookie tampering.
You are trying to access to an array value, you must use:
$result[8] and not $result(8)
Best regards!
Look at this - $result(8) (last row). A variable can't have arguments. You probably wanted $result[8] (9th element in array).
Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);
require("includes/connect.php");
$result = mysql_query("SELECT * FROM entries", $link);
while ($row = mysql_fetch_array($result)) {
htmlentities($row['quotes']);
}
I am trying to display data that is in the database, but I keep on getting:
Warning: mysql_real_escape_string() expects parameter 1 to be string
Is there anything wrong in the above code that is causing the problem? I am quite new to PHP and I am trying to understand what's going on and why it's doing it.
connect.php
$link = mysql_connect("localhost", "root", "");
if (!$link) {
die("Could not connect to the db");
}
mysql_select_db("ENTRIES", $link);
(I'm working on this locally, so user/pass really isn't important right now)
I don't see the point with escaping the above query, but you could do it like this:
$result = mysql_query(mysql_real_escape_string("SELECT * FROM entries"), $link);
You should read the documentation: mysql_real_escape_string()
As the error explains mysql_real_escape_string() takes a string as a parameter. In your code you posted as a comment you are passing $link which isn't a string, it's a database connection.
As #kristen, has said to solution should be to wrap you sql statement like so
$result = mysql_query(mysql_real_escape_string("SELECT * FROM entries"), $link);
If you are still receiving the error after this, you must be using the function elsewhere.
I am using a simple PHP script for the activation part of one of my applications. The applications posts one variable to the page (http://validate.zbrowntechnology.info/WebLock.php?method=validate). The variable is the serial number, posted as 'Serial'. Each time I post to this page, it returns Invalid. Here is the code:
<?php
$serial = $_POST['Serial'];
$method = $_GET['method'];
$con = mysql_connect("HOSTHERE", "USERHERE", "PASSHERE");
if(!$con) {
die('Unable to connect to MySQL: ' . mysql_error());
}
if($method == "validate") {
mysql_select_db("zach_WebLock", $con);
$query = "SELECT Key, Status FROM Validation WHERE Key='".mysql_real_escape_string($serial)."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
echo "Valid";
} else {
echo "Invalid";
}
} else {
echo "Unkown Method";
}
?>
Here Is The Error From PHP,
PHP Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
Right after the query use mysql_error() to see what happened. And Key is a bad choice for a column name because it's a reserved word in SQL. You can enclose it in `` to tell MySQL it's an identifier. Do some more debugging like this:
...
if (!mysql_select_db("zach_WebLock", $con)) die('mysql_select_db failed');
$query = "SELECT `Key`, Status FROM Validation WHERE `Key`='".mysql_real_escape_string($serial)."'";
print "query=$query<br>\n";
$result = mysql_query($query, $con);
print "error=" . mysql_error($con);
...
You're missing a closing parenthesis on this line:
if(mysql_num_rows($result) > 0 {
Is that missing in your code or just your question?
You may also want to add
if (!$result) {
print mysql_error();
}
after your query
Try Like This
$query = "SELECT Key, Status FROM Validation WHERE Key='".$serial."'";
What happens if at the last line you add this?
else echo 'Unknown method';
What may be happening is that $_POST and $_GET are not getting populated, this is a setting in php.ini, if I remember correctly (search for "superglobals" in the php docs).
edit: also, you have a very bad security risk there, google "sql injection". Basically the problem is that you could get any SQL directly into your database, and if the php user has enough permissions it could mean that anyone can, for example, delete all the data from your Validation table. You should at least do something like this:
$query = "SELECT Key, Status FROM Validation WHERE Key='".addslashes($serial)."'";
It could be a typo but you are missing a closing parenthesis here:
if(mysql_num_rows($result) > 0 {
^
And you might have turned off you error reporting, in which case you get a blank page.
Try echoing $serial:
echo $serial;
And is it what you typed in form?