php/mysql query problem - php

Can anybody tell me what's wrong with the following code ---
for($i=0; $i<count($strnamearray); $i++){
echo $strnamearray[$i]."<br />";
$cordcquery = "SELECT `lat` , `lng` FROM `traffic` WHERE `strname` = '{$strnamearray[$i]}' LIMIT 0 , 30;";
$cordresult = mysql_query($cordcquery);
if (!$cordresult)
{
die('Invalid strncquery: ' . mysql_error());
}
while($cordrow = #mysql_fetch_assoc($cordresult)){
echo $cordrow['lng'].",".$cordrow['lat'];
echo "<br />";
}
}
Here $strnamearray[$i] is an array which contains some name. there is no error showed after executing this php code. But the problem is i am not getting my desired output...

This is a shot in the dark here with out some more information but two things.
echo $cordcquery just to make sure the sql looks right and you can execute it directly in MYSQL. From what I can tell it should but without knowing whats in the variables I'm not sure.
Instead of LIMIT 0, 30 use just LIMIT 30. Should be the same thing but I have seen some funkiness depending on what versions of php and mysql you are using with passing LIMIT offset, row count. From what I can remember it would take the offset and not parse the row count and therefore would not return any information.
Let me know if this helps.

Related

MySQL query's suceed in PHPMyAdmin but not in the PHP Script itself

Just while playing around with Querying in PHP i ran into some trouble. The title of this post explains the problem. When i run a query in PHPMyAdmin the results will be different from the results i get in the PHP program itself. Here is the code i am using. Sorry if it looks a little odd i've been cutting and pasting things all over the place in a frantic attempt to get it working.
$connect = array('username'=>'root', 'host'=>'127.0.0.1', 'password'=>'');
$link = mysql_connect($connect['host'], $connect['username'], $connect['password']) or die('Error creating link: ' . mysql_error());
mysql_select_db('testing_pages', $link) or die('Error connecting to database: ' . mysql_error());
$sql = "SELECT `name` FROM `names`";
$query = mysql_query($sql, $link) or die('Query Failed! Check error:<br/><br/>' . mysql_error());
$query_2 = mysql_fetch_array($query);
$query = $query_2;
$loop = count($query);
$count = 0;
while($count <= $loop) {
echo $query[$count] . '<br/>';
$count++;
}
see, what im trying to get it to do is read all the names, pop it into an array, then print them out with a while loop. But it only seems to return 1 result and thats the first name in the databse. but when i run the EXACT query through phpmyadmin it will return every name in the database... Another odd thing, when using the 'count' function to get the number of values in the array is claims that there are 3 values, but during the loop it just prints out the first name, then for the second two it returns an 'Undefined index'.
Hope i dont seem like a noob right now... And i hope i explained everything well. Thanks to anyone who can help.
mysql_fetch_array fetches one row in the form of an array. Here are the docs.
And pay attention to that big warning message at the top of the page when you read the docs...

Display single result from database where ID matches using mysql and php

I am having some trouble displaying a single field from the db based on an ID number.
I want to trying to display the "C_Type_of_Referral" if the ID matches. I am sure the code is a mess of crap but I am still at the VERY early stages of learning how to do things in mysql and php.
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = '70'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
list($C_Type_of_Referral) = mysql_fetch_array($result);
Then I am trying to display the result using the code below:
echo ((isset ($_POST['C_Type_of_Referral']) && $_POST['C_Type_of_Referral'] == 'AS') || ($C_Type_of_Referral == 'AS'));
The code above returns the value of 1.
echo ($_POST['C_Type_of_Referral']);
The code above returns nothing.
Where am I going wrong?
Thanks for any help!
Let me start with: Use mysqli instead of mysql, especially when you are starting. Mysql is getting outdate, so start with the right one :)
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = 70 LIMIT 1";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$fetch = mysql_fetch_assoc($result);
echo $fetch['C_Type_of_Referral']; // <- this is what you are looking for
if( $fetch['C_Type_of_Referral']=='AS'){ echo 'AdServices'; }
elseif( $fetch['C_Type_of_Referral']=='VS'){ echo 'VisServices'; }
else{ echo 'Nothing of the kind'; }
Things I've done:
- removed quotes arround 70. Integers should not use quotes.
- Added 'limit 1'. This will speed things up in the long run. If you want 1 line, use limit 1
- Changed fetch_array to fetch_assoc ( you'll have to find out why yourself ;) )
Small note: keep table and columnnames lowercase, some systems might give you troubles when you use uppercase characters

Should this php function run recursively?

Im having problems with a method in a class file:
public static function getPageLeft($pid)
{
self::_dbConnect();
echo "now " .$pid;
$pid--;
echo " after ". $pid;
$data = mysql_query("SELECT id FROM evening_pages WHERE id='".$pid."'") or die(mysql_error());
$rows = mysql_num_rows($data);
if($rows == 1){
echo " in ";
return $data;
}elseif($pid != self::getMinPage()){
self::getPageLeft($pid);
echo " Current: " . $pid . " min: " .self::getMinPage();
}
}
I have the echos in there for debug only, and im getting:
now 22 after 21now 21 after 20 Current: 21 min: 1
This code is to find the next page left in a database driven CMS in case the client deletes a row from the database, it finds the next lower value.
So page id is 22 that your on, looks for id 21 in database, if its not there it should return 0 for the rows and move on and try again but on id 20, but there IS an entry for id = 20.
Anyone spot any issues with the code?
Also getting this error when it tries to find a page which doesnt exist before the current page, eg on page 22 but there is no ID for 21:
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/prelas/public_html/index.php on line 37
the code there is (line 37 is while):
$getPageLeft = sql::getPageLeft($pid);
while($row = mysql_fetch_array($getPageLeft)){
$pageleft = $row['id'];
}
Many thanks.
Just a quick edit: " in " never gets echoed, but yet when there is no deleted pages the navigation works fine.
Further edit: The code which makes use of the code (by like 37):
$navigation = '<div id="direction">
<span class="inNav"> << < </span><span class="black">•</span><span class="inNav"> > >></span>
</div>'
So you can see it uses $pageleft in there however when its dealing with blank pages the value is nothing (empty).
why don’t you write the SQL statement to get the next lower ID? For example:
SELECT `id`
FROM `evening_pages`
WHERE `id` < ?
ORDER BY `id` DESC
LIMIT 1
Or:
SELECT MAX(`id`)
FROM `evening_pages`
WHERE `id` < ?
That way, you only have to check if something has been returned by the query. Less code, less overhead for database requests.
The mysql extension is being phased out. Learn about using mysqli or PDO, and read up on the dangers of SQL injection.

PHP array_sum not working

I am trying to query an SQL table, and then have all the values from one column (it's a "tinyint(1)") added up and then printed, using array_sum. (Currently there are only two rows).
When both rows have a "1" in that column, it gives 2, the correct answer. And when they are both "0" it gives 0, correct again. But when one is "1" and one "0" it gives 2, not 1.
This is my code
$con = mysql_connect("XXX","XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXX_test", $con);
$day = $_GET["day"];
$query = mysql_query("SELECT $day FROM sites");
if (!$query)
{
die('Could not query: ' . mysql_error());
}
$rows = mysql_fetch_array($query);
echo array_sum($rows);
mysql_close($con);
?>
Thanks for any help.
--UPDATE--
I just solved this myself.
With this, if you want to know:
$query = mysql_query("SELECT name, SUM($day) AS Alerts FROM sites");
while($row = mysql_fetch_array($query))
{
echo $row['Alerts'];
echo "<br />";
}
This in fact never works correctly.
$rows = mysql_fetch_array($query);
That line only ever fetches the first row. The second row is never retrieved.
The reason it gives 2 using array_sum is that mysql_fetch_array gets the result in two different formats, with keys both by name and number. So you'll get something like this:
array(
0 => '1',
'Tuesday' => '1'
)
Obviously this will always be 2 or 0.
You should almost certainly do a count on the DB server:
SELECT COUNT(*) FROM sites WHERE $day=1
Note, however, that your biggest current problem is the enormous gaping SQL injection hole. Sanitise your input.
mysql_fetch_array() only fetches one row at a time. You need to fetch the rows in a while loop. Then you can either append the results to an array and sum those, or sum them in the loop. You can also SUM in mysql anyway, so you might look into using that.
I'm also obligated to suggest that you use PDO or some other DB wrapper instead of mysql_. You also need to escape variables you use in queries under most circumstances, especially if they come from _GET.
I would suggest doing it in the mysql query:
SELECT SUM($day) FROM sites
also, please escape the $day variable.
More of a comment:
array_sum can not work with the array you're passing to it. You need to pass an array for what the function actually works, like array(1, 2, 3) which will give you 6 then.
Next to that, let MySQL itself calculate the SUM (or COUNT?), so it's easier to handle in your script as others have posted.
I just solved this myself.
With this, if you want to know:
$query = mysql_query("SELECT name, SUM($day) AS Alerts FROM sites");
while($row = mysql_fetch_array($query))
{
echo $row['Alerts'];
echo "<br />";
}

Query that works in SQL but not in PHP

I am having trouble with an SQL query that I have inserted into a piece of PHP code to retrieve some data. The query itself works perfectly within SQL, but when I use it within my PHP script it says "Error in Query" then recites the entire SQL statement. If I copy and paste the SQL statement from the error message directly into MySQL it runs with no errors.
From my research I believe I am missing an apostrophe somewhere, so PHP may be confusing the clauses, but I am not experienced enough to know where to insert them.
The query is using a variable called $userid which is specified earlier in the PHP script.
$sql= <<<END
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_B.seller, Table_B.final_price
FROM Table_A
INNER JOIN Table_B ON Table_A.id=Table_B.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
UNION ALL
SELECT sum(final_price)
FROM (
SELECT Table_A.rated_user_id, Table_C.seller, Table_C.final_price
FROM Table_A
INNER JOIN Table_C ON Table_A.id=Table_C.id
) AS total_bought
WHERE seller != $userid
AND rated_user_id = $userid
END;
After this section the script then goes on to define the output and echo the necessary pieces as per usual. I'm happy with the last part of the code as it works elsewhere, but the problem I am having appears to be within the section above.
Can anyone spot the error?
Edited to add the following additional information:
All of the fields are numerical values, none are text. I have tried putting '$userid' but this only makes the error display the ' ' around this value within the error results. The issue remains the same. Adding parenthasis has also not helped. I had done a bit of trial and erorr before posting my question.
If it helps, the last part of the code bieng used is as follows:
$result = mysql_query($sql);
if (!$res) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
$total_bought = 0;
while ($row = mysql_fetch_array($result)) {
$total_bought += $row[0];
}
$total_bought = number_format($total_bought, 0);
echo '<b>Your purchases: ' . $total_bought . '</b>';
echo "<b> gold</b>";
You're checking !$res, it should be !$result:
$result = mysql_query($sql);
if (!$result) {
die('Error: ' . mysql_error() . ' in query ' . $sql);
}
I suppose, you're echo()ing the query somewhere and copy-pasting it from the browser. Could it be that the $userid contains xml tags? They wouldn't be displayed in the browser, you would have to view the page source to spot them.
you should test with $userid quoted, and parentheses around the two statements.
I'm assuming that rated_user_id is a numeric field, but what type is seller? If it's a character field, then $userid would have to be quoted as streetpc suggests.
Another thing to check is that you have at least one space after the end of your lines for each line of the query. That has tripped me up before. Sometimes when going from your editor/IDE to the database tool those problems are silently taken care of.

Categories