Sql Variable PHP Inclusion Issue - php

Hi I'm having trouble adding a variable to my Sql script, if i replace $safe with 'text' it works fine, i guess its a simple synatax problem. I hope someone can help as i'm a bit of a newbie!
<?
$ORDERID = 'LH-PAY-'.rand(10000000,99999999);
$safe - mysql_escape_string($ORDERID);
mysql_connect("localhost", "youthtra_wp1", "pass") or die(mysql_error());
mysql_select_db("youthtra_wp1") or die(mysql_error());
$query = "INSERT INTO tblPayments (PaymentID,Created,Status,Type,FlgID,WpUser,FullAmount,InsuranceAmount) VALUES ('".$safe."',now(),'Started','edpq','12345678','LH23456','499.99','19.99' )";
mysql_query($query);
echo 'ok';

Some points:
a) $safe is anything but. mysql_escape_string() is NOT safe to use. That's why mysql_real_escape_string() exists.
b) You shouldn't be using the mysql_*() functions anyways
c) You're simply assuming your query will always succeed, and are deliberately IGNORING the return value of mysql_query() which could help you if/when things fail. e.g. your code should be, at minimum:
$result = mysql_query(...);
if ($result === FALSE) {
die(mysql_error());
}

Just fix the - for = on line 3:
$safe - mysql_escape_string($ORDERID);

Related

Checking variable in database via php (if statements)

So after a long rest of coding(around 5months) i started to forgot some of the codes and i need help with this one, i cant find in the google with this topic, etc
code :
<?php
$num1 = "0";
$database = mysql_connect('x', 'x', 'x') or die ("Error x01");
mysql_select_db('x') or die ("Error x02");
$SQL1 = "Select * FROM 'server_status' WHERE on = '$num1'";
$result_id1 = #mysql_query($SQL1) or die("DATABASE ERROR!");
$total1 = mysql_num_rows($result_id1);
if($result1){
echo "Server is under maintenance";
}
?>
right here i have a code where i'am gonna check the variable "on" in "server_status" table in my msql
somehow even when i have my "on" variable on 0 (int not bool [join_protection is on int too]) it still gives out the die which is
or die ("DATABASE ERROR!");
i can't find how to fix that i played around with it and not managed to make it work
here's the result
i'm looking forward for your answer
thanks for passing by and helping me
regards,
-itsproinc
You're using single quotes which are not the correct Identifier Qualifiers around your table name, remove them.
FROM server_status
or use ticks: (which resemble quotes, but are not the same).
FROM `server_status`
Plus, you are using a MySQL reserved word, being on for your column name and it needs to be wrapped in ticks.
$SQL1 = "Select * FROM `server_status` WHERE `on` = '$num1'";
Plus, as I stated in comments:
This doesn't help you or die ("DATABASE ERROR!"); this does mysql_error() and remove the # in #mysql_query it's an error suppressor.
Deprecation notice:
mysql_ is deprecated and will be removed from future PHP releases.
Use mysqli_ or PDO.
Better yet:
Use mysqli with prepared statements, or PDO with prepared statements, they're much safer.

PHP mysql query syntax errors

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.

Logging $_SERVER to mysql

I use this code , to log $_SERVER['REMOTE_ADDR']; to my small db
my issue is value never saved to db , cant figure what i missed in the code
Any tips ?
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs(REMOTE_ADDR,) VALUES ('$ip')";
}
echo $_SERVER['REMOTE_ADDR'];
?>
This should work. In addition to the other comments here, you had a comma (,) too much in your query.
<?php
mysql_connect("localhost", "usr", "passwd");
mysql_select_db("db") or die ( 'Can not select database' );
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO logs (REMOTE_ADDR) VALUES ('$ip')";
mysql_query($sql);
}
initCounter();
?>
You aren't actually executing the query. You create the SQL but don't use mysql_query($sql)
You have a comma at this point in the SQL REMOTE_ADDR, <-- remove that
When you execute the query, use mysql_error() to test for an error message (and check the result of mysql_query() for a boolean false.
Finally I would suggest switching to MySQLi or PDO.
If that's you're full code... there is one thing missing you actually need to EXECUTE the query...
mysql_query($sql);
EDIT:
I have just noticed, you're connecting to the DB OUTSIDE of the function trying to run the Query... obviously it will fail as inside the function, it has no awareness of the DB connection.

Basic SQL output question

this is probably the most basic question in the world, but I cannot figure it out.
I would like to simply display a users First name, and Email adress from my table. I have tried using a loop, but that was entirely worthless considering I am only selecting one row. I know this is a menial question but I could not find/remember how to do it. Thank you!
$db = mysql_connect("server","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT FirstName, EmailAddress"
. " FROM Student"
. " WHERE StudentID = '$student' ";
$result = mysql_query($sql, $db);
$num = mysql_num_rows($result);
$userinfo = mysql_result($result,$userinfo);
$student is a session variable. I want to echo the First name and email address somewhere in the page, but I cannot believe how much pain thats causing me. Thanks again!
mysql_fetch_assoc() turns a result row into an array.
$result = mysql_query($sql, $db);
$user = mysql_fetch_assoc($result);
echo $user['FirstName'];
echo $user['EmailAddress'];
It looks like you spelled address wrong, so it probably doesn't match your real column name. More importantly, your code appears vulnerable to SQL injection. You really need to use prepared statements (see How to create a secure mysql prepared statement in php?) or escaping.
To fetch a row, you must use one of the mysql_fetch functions (e.g. mysql_ fetch_ array, mysql_ fetch_ object, etc.)

Posting variable returns invalid

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?

Categories