Please help me regarding the specified problem:
The code section:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='$_GET[id];'");
// the above query is not working
if ( mysql_num_rows($result) == 0 ) {
print "<p>No events right now.</p>\n";
}
else {
$lasteventmonth = '';
while ($row = mysql_fetch_array($result)) {
$eventmonth="";
$eventmonth = date("F Y",$row['eventdate']);
if ($lasteventmonth != $eventmonth) {
print "<p style='font-size: 18px;'><b>$eventmonth</b></p>";
}
$lasteventmonth = $eventmonth;
showEvent($row);
}
}
?>
........................
........................//other codes
when the code evaluates as follows:
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Users\Fagun\Desktop\UsbWebserver\Root\mapcal\mapcal.php on line 122
No events right now.++++++++
After your call to mysql_query, use this:
if (! $result) {
echo mysql_errno() . ": " . mysql_error(). "\n";
}
this will tell you exactly, why MySQL won't run your query.
is ID a String or int? Either way I guess you shouldn't include a trailing semicolon?
Try changing it as follows...
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='$_GET[id]'");
I assume it's an issue with how you're using building the query and concatenating the id. Try this instead (notice how the ID is concatenated):
$query = "SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events
ORDER BY eventdate where
id='".$_GET[id]."'";
$result = mysql_query($query) or die(mysql_error());
You don't have to break it into 2 pieces, but - this should be easier to read and understand. You can even echo out the query before running it to see what query is actually being created, and try it manually on your database.
The or die(mysql_error()) part will give you specifics on what the issue is (if it wasn't the ID issue).
Quote values properly :
$_GET[id] should be $_GET['id']
Try below:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='".$_GET['id']."');
Try this:
"SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events ORDER BY eventdate where
id='".$_GET['id'].";'"
I'm assuming that id does not come from user input. If it does, this is vulnerable to a SQL injection attack.
try:
$result = mysql_query("SELECT *,
UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate
FROM events
ORDER BY eventdate
where id= '" . intval($_GET['id']) . "'");
if($result)
{
//Do code
}
use intval() to make sure $_GET['id'] is an integer.
use the if statement to make sure the query has executed correctly.
Try this
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where
id='".$_GET['id']."' ORDER BY eventdate");
Related
I have a simple function that returns a count from a database table, based on some criteria.
function MyCount($strTable, $strCriteria) {
$strSQL = "SELECT COUNT(*) FROM " . $strTable . " ";
if (trim($strCriteria) != "") $strSQL .= "WHERE " . $strCriteria;
$results = mysql_query($strSQL, $objConn);
$row = mysql_fetch_array($results);
return $row[0];
}
Its very useful for quickly getting a value in 1 line of code, e.g:
$Users = MyCount("Users", "Deleted = 0");
However, I'm now trying to move to PDO and am having trouble passing in the were as parametrized values. I'm trying to do something like the below (which doesn't work):
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE :criteria");
$objQuery->bindParam(':table_name', $strTable);
$objQuery->bindParam(':criteria', $strCriteria);
I guess the obvious would be:
$objQuery=$objConn->prepare("SELECT count(*) as TheCount FROM :table_name WHERE ".$strCriteria");
$objQuery->bindParam(':table_name', $strTable);
But, this seems to go against the spirit of parametrized values... does anyone have any other suggestions?
Thanks
This line is the issue:
$objQuery->bindParam(':table_name', $strTable);
You can only bind values ( field= :value) in PDO you cannot bind table names or column names or custom dynamic where clause.
So you just build the query manually:
SELECT count(*) as TheCount FROM `$strTable` WHERE $strCriteria
function my_count($strTable, $strCriteria, $objConn)
{
$sql ="SELECT count(*) as TheCount FROM $strTable WHERE $strCriteria";
$objQuery=$objConn->query($sql);
$row =$objQuery->fetch();
return $row['TheCount'];
}
$Users = my_count("Users", "Deleted = 0", $objConn);
i want to pass limit value in my select query through user,can anybody help me to do this???? thanks in advance![][1]
$result = mysql_query("select distinct * from tweet_info ".
"where MATCH(tweet) ".
"AGAINST('".$search."')ORDER BY created ", $con);
lets just say that the user input is "LimitInput" then :
$limit = $_POST['LimitInput'];
$result = mysql_query("select distinct * from tweet_info ".
"where MATCH(tweet) ".
"AGAINST('".$search."')ORDER BY created limit 0,".$limit, $con);
$result = mysql_query("SELECT DISTINCT *
FROM tweet_info
WHERE MATCH(tweet)
AGAINST('" . $search . "')
ORDER BY created LIMIT 0,1 DESC", $con);
Just add a limit to the end, this will grab the first result found.
You shouldn't really be using the mysql_query function anyway, it's depreciated, maybe look into a different method, e.g. mysqli or PDO.
$u_id=$event_assoc['Uniqueid'];
echo $u_id."\n";
$result1 = mysql_query("SELECT * FROM eventdetail WHERE unique_id = '$u_id'", $con1);
while($row = mysql_fetch_array($result1))
{
echo 'in eventdetail'."\n";
$e_id= $row['event_id'];
$destination= $row['destination'];
$uniqueid= $row['unique_id'];
$call_num= $row['channelid'];
}
echo mysql_num_rows($result1);
echo $e_id."\n";
echo $destination."\n";
echo $call_num."\n";
echo $uniqueid."\n";
if(mysql_num_rows($result1)>0)
{
echo 'calculate'."\n";
$result= mysql_query("SELECT sum(billsec)
FROM cdr
WHERE uniqueid = '$uniqueid'", $con2);
$bil = mysql_fetch_array($result);
$bill= (float) $bil['sum(billsec)'];
echo $bill."\n";
this is my code..
whenever i try to execute sum function query it retruns top row's billsec instead of addition of all row's billsec
You are doing a where on an unique ID in the sum query. Remove the where and it'll work
You are using unique id in your query.. And in a table single row will have that id, thats why you are getting top row's billsec... Remove the where clause in second query, and then check.
$result= mysql_query("SELECT sum(billsec)
FROM cdr
WHERE uniqueid = '$uniqueid'", $con2);
i guess there is a bug in this area...look again
The PHP statement for the SQL SUM Query should be:-
$result= mysql_query("SELECT sum(`billsec`), `uniqueid` FROM `cdr` GROUP BY `uniqueid` HAVING `uniqueid` = '$uniqueid'", $con2);
You need to use the clause "GROUP BY" whenever you are using any MySQL Aggregate functions (if needed). Also if you are using any aggregate functions (like "SUM", "MAX" etc), then you cannot use "WHERE" clause on the field (in this case, the field is "uniqueid") which is being used in the "GROUP BY" clause.
Hope it helps.
So I wrote this earlier (in php), but everytime I try echo $test", I just get back resource id 5. Does anyone know how to actually print out the mysql query from the variable?
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)") or die(mysql_error());
print $dave;
This will print out the query:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
print $query;
This will print out the results:
$query = "SELECT order_date, no_of_items, shipping_charge, SUM(total_order_amount) as test FROM `orders` WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)";
$dave= mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($dave)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
well you are returning an array of items from the database. so you need something like this.
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge,
SUM(total_order_amount) as test FROM `orders`
WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)")
or die(mysql_error());
while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset, mysql_query() returns a resource on success, or FALSE on
error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(),
and other functions for dealing with result tables, to access the
returned data.
http://php.net/manual/en/function.mysql-query.php
$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);
you can change
LIMIT 1
to
LIMIT any number you want
This will show you the last INSERTED row first.
I'm having trouble getting any information to display from this query. Anyone know where I'm going wrong?
Thank you!
$query = "SELECT * ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['users.user_id'];
echo $row['comments.comment'];
}
use mysql_fetch_assoc() instead of mysql_fetch_array().
In your loop use the column name as the array key:
while ($row = mysql_fetch_assoc($result)) {
echo $row['column_name1'];
echo $row['column_name1'];
}
In your query try to be more specific on the select statement, try not to use *.
You're probably getting the error because you are sorting (ORDER BY) on a field that does not exist in your query.
It would be best practice to not use the "SELECT *" querying. If all you need are specific values, specify them. This also helps when retrieving the data...
$query = "SELECT users.user_id, comments.comment, comments.date ".
"FROM comments, users ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['user_id'];
echo $row['comment'];
echo $row['date'];
}
It is good practice to specify column names in a query rather than using * - on some DBs there is a performance impact and on all it prevents any unexpected behaviour cropping up from table changes.
In the example I think the issue is arsing from the array keys you are using - you don't need to include the table name in them, just the column name:
echo $row['user_id'];
echo $row['comment'];
The better practice is to write only fields what you need in your sql query like this:
$query = "SELECT u.user_id uid, c.comment comment ".
"FROM comments c, users u ".
"WHERE comments.user_id = users.user_id ".
"ORDER BY comments.date DESC ".
"LIMIT 10";
Using so type of queries you reduce the time of executing your query and transmitting data from database server to your php script. After this modification your cycle transformed to:
while ($row = mysql_fetch_array($result)) {
echo $row['uid'], $row['comment'];
}
I use PDO method but this can work for you too:
<?php
$sql = "SELECT * FROM comments as c INNER JOIN users as u ON c.user_id=u.user_id WHERE u.user_id=:user_id ORDER BY c.date DESC LIMIT 10";
//prepare the connection to database
$prep = $conn->prepare($sql);
//change the parameters for user_id on WHERE condition you can put anything you want but i will put the user session id
$prep->bindParam(":user_id", $_SESSION['user_id']);
$prep->execute();
//ill use fetchAll function because it can be more than 1 comment
$datas = $prep->fetchAll();
foreach($datas as $data){
echo $data['user_id'];
echo $data['comment'];
echo $data['date'];
}
?>