problem with get url using php and mysql - php

Sorry if this question may seem easy to some but i cannot seem to figure it out. i was told that i could come here because the guys here are very helpful. i am having problem with the following code. when the uid is call into the url for example page.php?uid=5 i get "some code" if i do page.php?uid=letters i get redirected to page.php?uid=1. that works fine. but if a user should enter page.php?uid=1letters i get this error..Unknown column '1gh' in 'where clause'
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\page.php on line 173.
i only get this error if the user enters unwanted characters at the end of get url id. How can i prevent this from happen how can i have it redirect to page.php?uid=1... see code below
$id = mysql_real_escape_string(#$_GET['uid']);
$query = mysql_query("SELECT user.* FROM user WHERE id = '$id'");
if ((mysql_num_rows($query)==0)) {
header("location:page.php?uid=1");
die();
}
else {
while($rows = mysql_fetch_array($query)){
$foo = $row['foo'];
echo "some code";

mysql_query returns false on error. You should check what it returns:
$query = "SELECT user.* FROM user WHERE id = '$id'"
$result = mysql_query($query);
if ($result === false) {
die($query.'<br/>'.mysql_error());
}
Then you can understand why it failed. I've added the query to the die() statement so you can try the query manually as well.
The error given is unknown column of a string, which suggests you are not enclosing the value with single quotes in the SQL query, even though the code in the question does.
In production you should be taking all steps you can to ensure errors are handled gracefully. In this case you will probably want the same behaviour as not finding a user:
header("location:page.php?uid=1");

Related

table doesnt exist

I have created a query that loops through a group of table ID's to get a sum of their combined values. with error handling i get a "Table 'asterisk.custom_' doesn't exist" error and the query is killed obviously. but if i remove the error handling then i get an "mysql_fetch_array() expects parameter 1 to be resource" and the query completes as it should.
Thank in advance for your help.
include("currentday.php");
//---used for testing passing variables
//echo $customID[0];
//echo "<br>".$numrows;
$i = 0;
while($i<=$numrows)
{
mysql_select_db("asterisk") or die(mysql_error()); //This line determines the database to use
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
sum(vicidial_agent_log.pause_sec) as sumPause,
sum(custom_$customID[$i].d_amt) as sumDamnt,
sum(custom_$customID[$i].up_amt) as sumUpamnt,
sum(custom_$customID[$i].md_amt) as sumMdamnt,
sum(custom_$customID[$i].s_amount) as sumSamnt,
sum(vicidial_agent_log.dispo_sec)
FROM
vicidial_agent_log
INNER JOIN
vicidial_users
ON
(vicidial_agent_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$i]
ON
(vicidial_agent_log.lead_id = custom_$customID[$i].lead_id)
WHERE
vicidial_users.user = 'tcx'
GROUP BY
vicidial_users.full_name
ORDER BY
vicidial_agent_log.event_time DESC
";
$queryResult = mysql_query($query);// or die(mysql_error());
while ($rowResult = mysql_fetch_array($queryResult))
{
$pauseResult[] = $rowResult["sumPause"];
$sumdamntResult[] = $rowResult["sumDamnt"];
$sumupamntResult[] = $rowResult["sumUpamnt"];
$summdamntResult[] = $rowResult["sumMdamnt"];
$sumsamntResult[] = $rowResult["sumSamnt"];
}
//print_r($pauseResult);
//echo $pauseResult[0];
$i++;
}
Update:
The table exist in the database:
custom_2346579543413
custom_5466546513564
they are created by the dialer software and im calling them from another query that provides me the numeric part of the table name so this query loops through the values in customID array to make the query, Thanks again
Update:
Sammitch, thank you for the suggestion, however they did not work.
Solution:
Thanks Marc, you confirmed a suspicion i had in that it was looping correctly but for some reason it was looping more times that there we keys. so i echoed $i to confirm and in fact it was it was outputting 0,1,2,3 and since i know there is only 3 keys the last one didn't return anything and so error handling caught it and killed the entire loop and why it appeared correct when error handling was turned off. The solution was actually rather simple and it was in the while loop evaluation string i had used
while($i<=$numrows)
while($i<$numrows)//this worked, the equals part of that gave it an extra loop
and the query completes as it should.
No, it doesn't. "mysql_fetch_array() expects parameter 1 to be resource" means "the query failed, and you didn't bother to check before calling mysql_fetch_array()".
Your problem is that variable expansion inside of a string doesn't like array indexes. You need to change:
"sum(custom_$customID[$i].d_amt) as sumDamnt,"
To:
"sum(custom_{$customID[$i]}.d_amt) as sumDamnt,"
Or:
"sum(custom_" . $customID[$i] . ".d_amt) as sumDamnt,"
For it to work properly.

Combining conditions in SQL

I am using php and sql to check user information from the database. I need to check if the username and password is correct and the account is active. I have this sql query, but it does not work. What is the method to do it?
SELECT * FROM foo WHERE (name='foo' AND password='foo') AND active=1
for me
SELECT * FROM foo WHERE (name="foo" AND password="foo") AND active=1
should be same as
SELECT * FROM foo WHERE name="foo" AND password="foo" AND active=1
the above query assumes that field active is of family type int In case its varchar or char you r query should be like this
SELECT * FROM foo WHERE name="foo" AND password="foo" AND active='1'
and the query should work and i assume you are taking care of SQL injections from php
Where you say, "When I remove AND active=1 part, it works fine. Any ideas?"
Try changing it to AND active<>1 to see if the issue lies in that field. It's possible 'active' may be null or some other value. Try outputting the value (try var_dump($var) in PHP) to see what is returned for the 'active' field. If the value is 0, a blanck string, or null, then you've isolated your problem.
The query looks correct (assuming columns name, password, and active exist in table foo), but if you're using it in PHP you might be running into trouble with the double quotes if they're inside a string you're declaring. You might need to escape them or use single quotes.
My query returns 0 row and I am sure that I have that fields in the database and typing the correct information. When I remove AND active=1 part, it works fine. Any ideas?
Yes.
The idea is very simple. Just check if a record with name='foo' and password='foo' has active=1. Then correct mistake and your data
Hint: a programmer cannot be sure when the logic says he is wrong.
First of all, use mysql_real_escape_string() or a PDO method to escape your input. You do not want people messing around in your database.
A simplified version of what I normally do is
SELECT main.id,
main.isActive,
(SELECT count(sub.id)
FROM users AS sub
WHERE sub.id = main.id
AND sub.credential = 'md5password'
LIMIT 1
) AS credentialMatches
FROM users AS main
WHERE main.identity = 'username'
Grab your result:
$result = mysql_query($sql);
$data = array();
if (false !== $result) {
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
}
Handle your result:
if (count($data) < 1) {
// username not found
} else if (count($data) > 1) {
// multiple rows with the same username, bad thing
} else {
$row = $data[0]
if (false === (boolean) $row['isActive']) {
// user not active
} else if (true === (boolean) $row['credentialMatches']) {
// SUCCESS
// valid user and credential
}
}
Also note: ALWAYS store password at least as an MD5 hash like so WHERE credential = MD5('password'). Same when you are inserting: SET credential = MD5('password'). This way, when someone else will ever read you database, user passwords won't be revealed so easily.
An even better is to add an additional salt to hash, but that might be going to far for now.
You could debug your sql like this in php:
$sql = "SELECT * FROM foo WHERE (name='foo' AND password='foo') AND active=1";
$result = mysql_query($sql) or die (mysql_error());
This "or die (mysql_error())" will give you the exact error of that query, maybe the DB isn't selected if that happened use mysql?query($sql, $db)...
Hope it helps

How to get url ID in PHP? (for mysql_query UPDATE)

I want to add an edit button for a script called spiral url, but the problem is that I can't get the URL id. This is what I've tried:
/** get url id **/
$id = isset($_GET['id']) ? $_GET['id'] : '';
#mysql_query("UPDATE short_urls SET long_url = 'test' WHERE url_id = '".$id."' LIMIT 1");
What am I doing wrong?
Also I emailed the author and his response:
"I recommend you post on Stackoverflow - https://stackoverflow.com/.
I would love to help you but I don't see what you are doing wrong. I'm still learning PHP as well."
You're wide open to SQL injection attacks.
You're supressing errors with the # operator. NEVER suppress errors
You're not checking the return value of mysql_query(), which returns a boolean FALSE on failure.
Scrap that code and use this:
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$sql = "UPDATE short_urls SET long_url = 'test' WHERE url_id=$id LIMIT 1";
$result = mysql_query($sql);
if ($result === FALSE) {
die("Mysql error: " . mysql_error() . $sql);
}
Note that I'm assuming that the id parameter is numeric. If it's not, then remove the intval() stuff.
Make sure the value of $_GET['id'] actually has a value. Your URL will look something like http://myurl.com/index.phtml?id=yourvalue. You can do this by doing a:
print "id=".$_GET['id'];
Also, whenever doing a query, please be sure to escape any and all variables that can be manipulated by the user. Without doing this, you're opening yourself up to SQL injection attacks.
mysql_real_escape_string - http://php.net/manual/en/function.mysql-real-escape-string.php
#mysql_query("UPDATE short_urls SET long_url = 'test' WHERE url_id = '".mysql_real_escape_string($id)."' LIMIT 1");
If the url is like this: domain.com/something.php?id=65
$_GET['id'] should be equal to 65
if there is no id there then when you try to access $_GET['id'] you will get an error.
Also try removing the # symbol (that suppresses PHP warning).
And you are waaaay open to bobby-tables
Also (side note), get a new developer who knows what they are doing ;-)
Have you checked the url
http://www.somewebsite.com?id=56&other_car=test
specifically for the "?" after the end of the url and also check all the parts are broken up by the ampersand.
failing that you can view all of your available get array variables by
print_r($_GET);

PHP data retrieving problem in database

Ok so the problem is... i m a newbie and i m trying to understand what is happening.Im sending through an html form this data(name,email) using POST in a database.I understand the logic behind it all but what basically happens is that everytime I enter a name,any name,it echoes the else statement:"there is already a user with that name". and it sends back the first name in the database.when there s nothing,it sends nothing. So here's the chunk:
$query= "SELECT* from users where username='".$_POST['name']."'";
$result = mysql_query($query);
if (!$result){
$query = "INSERT into users (username, email, password) values
('".$_POST["name"]."', '".$_POST["email"]."',
'".$passwords[0]."')";
$result = mysql_query($query);
if ($result){
echo "It's entered!";
} else {
echo "There's been a problem: ".mysql_error();
}
} else {
echo "There is already a user with that name: <br />";
$sqlAll = "select * from users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
You may want to check mysql_num_rows() rather than checking for !$result, I think that if the query is sucsesfull you'll get a resource back, even though it contains zero rows.
You may also want to read up on: http://php.net/manual/en/security.database.sql-injection.php
ESCAPEEEEE
Firstly, you need to learn about escaping.
Have you never heard of little Johnny DROP TABLES?
http://xkcd.com/327/
Serious business
The reason why it always returns, is because the response in $result is actually a resource data type. And that will always when cast as a boolean be true. (And since your query shouldn't fail).
You should fetch the result. For example. (This isn't the best way, but it is a way to do it).
mysql_fetch_row(result)
Per the manual, mysql_query will return false when there is an error - "For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error."
see no violation in your code. first mysql_query executes with no error and always returns true. try to test returned rows count like this:
if (mysql_num_rows($result) == 0) {
//insert record
} else {
// show alreay exists
}
First of all, you are testing for:
if (!$result)
which will evaluate to true only if the query fails.
You should also sanitize all input before using it in SQL queries.

MySQL Query Enum

I have been working on this for a while now, I know it's simpler than what I am making it, but I just can't get it. I have some code where I am trying to query an enum either 1 or 0 from my table so this is exactly what I have to do this.
$username = 'test'
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='.$username.'");
Now I have all the connection stuff down I think, I get no errors there, but when I print this thing out in my echo I get this,
Heres my echo:
echo 'Hello, '.$username.', you Result is: '.$passResult.'!';
What I want to get is:
Hello, test, your Result is: 1
or
Hello, test, your Result is: 0
Now what I get is:
Hello, test, your Result is: Resource id #6
Now no matter what I do I get the same thing, I have no idea what I'm doing wrong here guys if someone could point this out that would be awesome. What this enum is being use essentially for a boolean just to see if the user has personally set a password not the computer generated version.
mysql_query returns a result resource, essentially a pointer to the memory where the results are buffered. That result set can contain many rows, as you can select many rows, so you need to fetch the row(s) you want then the column(s) you want from those rows.
/* execute the query and get a result resource back */
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='" . mysql_real_escape_string($username) . "'");
/* retrieve the first row from $passResult */
$row = mysql_fetch_assoc($passResult);
/* assign the usrSetPass column's value from that row to $passed */
$passed = $row['usrSetPass'];
Also, your query is wrong. You enclosed it in double quotes, so you're not actually breaking out of the string and concatenating $username when you use the single quotes and dots inside. I've corrected it above.
mysql_query doesn't return a value, it returns a resource (see here in the manual).
The returned result resource should be passed to another function for dealing with result tables (like mysql_fetch_array() or mysql_fetch_assoc()), to access the returned data.
Example based on your initial code:
$username = 'test';
$passResult = mysql_query("SELECT usrSetPass FROM members WHERE usr='".$username."'");
while ($row = mysql_fetch_assoc($passResult)) {
echo $row['usrSetPass'];
}

Categories