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?
Related
I want to get stings form a mysql server to use as text on my webpage.
That way I can edit the text without editing the html file.
Problem is that the code I have to get the string is quite long, and I don't want to paste it everywhere on the page.
I would also like a tip on how to get just one datafield from the server, and not the whole column like I do here.
So this is what I got. And what I think is to write a function I can call from all the places I want the webpage to get a string or field from the sqlserver. But I don't know how. Can anyone help me?
<?php
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else
{
echo "error";
}
$con->close();
?>
Problem is that the code I have to get the string is quite long, and i
dont want to paste it everywhere on the page.
Put the code into a function, call that function wherever you need to. Then it is just a single line you have to insert.
PHP:
<?php
function connect() {
$con=mysqli_connect("localhost","user..", "passwd..","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return $con;
}
}
function renderContent($con) {
$sql = "SELECT topic FROM web_content";
$result = $con->query($sql);
if ($con && ($result->num_rows > 0))
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo $row["topic"]. "<br>";
}
} else {
echo "error";
}
}
HTML:
<?php $con = connect(); ?>
[...]
<div>
<?php renderContent($con); ?>
</div>
[...]
I would also like a tip on how to get just one datafield from the
server, and not the whole coloumn like i do here.
Not the whole column would mean not all rows, but one or some selected ones. That means you are looking for sqls ''WHERE'' clause.
SELECT topic FROM web_content WHERE <where clause>;
Where <where clause> is some clause to narrow down the result set. For example you can narrow down to topics containing some string: ... WHERE topid LIKE '%word%'; or by the IDs are a date range of the entries in your table. You should take a look into the documentation of the query syntax for an explanation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Obviously all of this is just a rough sketch of what you are looking for. Lots of things need improving. Using exceptions for error handling is one thing, just to give an example...
I wrote this line of code, but i do not know what happened. I have looked all around the internet for the solution, but none of them seem to fix my issue. I get:
Warning: mysql_query() expects parameter 1 to be string, resource given in /home/mylittle/public_html/style1.php on line 12
yes
When i enter the page. It does not update the style thing in my database. Please help me. I am desperate!
$dbewds = mysql_connect("localhost","mylittle_pony","lol123", "mylittle_pony") or die("Couldn't connect!");
if ($_SESSION['username']) {
$unw = $_SESSION['username'];
$style = 1;
mysql_query($dbewds,"UPDATE `users` SET `style` = '".$style."' WHERE `username` = '".$unw."'");
echo "yes";
} else {
echo "no";
}
?>
$dbewds = mysql_connect("localhost","mylittle_pony","lol123") or die("Couldn't connect!");
mysql_select_db("mylittle_pony");
if (isset($_SESSION['username'])) {
$unw = $_SESSION['username'];
$style = 1;
$query=mysql_query("UPDATE `users` SET `style` = '".$style."' WHERE `username` = '".$unw."'",$dbewds);
if(!$query){
die("query failed".mysql_error());
}
echo "yes";
} else {
echo "no";
}
the connection should be the second variable
I would advise the steps you debug the likely problems next time:
1. try to understand the warning/error message
for example: "mysql_query() expects parameter 1 to be string, resource give", so figure what is a string, what is a resource, according to your code
2. read the manual
go to http://us2.php.net/manual/en/ and search "mysql_query", you can get http://us2.php.net/manual/en/function.mysql-query.php, so figure out how to use the function,
pay attention to the parameters and return, and run the examples under the function intro
3. check your code
btw, mysql_query() will be deprecated as of PHP 5.5.0, MySQLi or PDO_MySQL is better.
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).
I am using the following script to check a code, so when the user enters the survey code they get the survey that is associated with that code. The part that fetches the survey is working as its supposed to, but I cant seem to get the error message to come up for some reason. If I enter a wrong code or no code all on the form this posts from, all I get is a blank page.
<?php
$con = mysql_connect("myhost","myuser","mypassword;
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Select mysql db
mysql_select_db("mydb", $con);
$questionaireID = $_POST['questionaireID'];
$result = mysql_query("SELECT * FROM itsnb_questionaire WHERE questionaireID='$questionaireID'") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
if (empty($row['questionaireID'])) {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
} else {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
}
}
?>
It will never get there, because if the resultset is empty, it'll skip the while loop.
Try this, instead, limiting to 1 record (which is what you expect) and using an if...else instead of your while (while is only required when multiple results are expected):
$sql = "SELECT *
FROM itsnb_questionaire
WHERE questionaireID = '{$questionaireID}'
LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if ($row = mysql_fetch_array($result)) {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
} else {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
}
If number of returned rows is zero than you haven't found your result therefore you can display apropriate error message
try
if (mysql_num_rows($result)<1){
//error
}
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());