I’m just learning MYSQL / PHP. I’m having trouble with a query, it’s working in myphpadmin:
select `email`, count(*) as count
from `table`
where `date` = "open"
group by `email`
order by `email`
I can’t get it to work if I either write the mysql_query myself or use the php myphpadmin generates:
$sql = "select `email`, count(*) as count\
. "from `table`\n"
. "where `date` = \"open\"\n"
. "group by `email`\n"
. "order by `email`\n"
. "";
The purpose is to query a three column table of EMAIL, DATE, EVENT – where EVENT could be “open” or “bounce” and count the number of times a person opened an email.
Here’s the rest of the file (I realize I should be using msqli, that’s next on my list to figure out….):
<?php
$db_host = '123';
$db_user = '123';
$db_pwd = '123';
$database = '';
$table = 'test';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
sql = "select `email`, count(*) as count\n"
. "from `table`\n"
. "where `date` = \"open\"\n"
. "group by `email`\n"
. "order by `email`\n"
. "";
// sending query
$result = mysql_query($sql);
if (!$result) {
die("Query to show fields from table failed 2");
}
echo "<table border='1'>
<tr>
<th>email</th>
<th>event</th>
<th>date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Email'] . "</td>";
echo "<td>" . $row['event'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
}
echo "</table>\n";
mysql_free_result($result);
?>
I just get the “Query to show fields from table failed 2” back – the query didn’t work
The ‘\n’ in your query – was generated by myphpadmin (when I use the “generate php code” feature
I have a connection to the database, I just changed the value assigned to those variable so I wouldn’t post them
I have the “$” in the $sql var in my file, just didn’t get it copied over here.
So,
When I replace this query with a simple one, it works fine, but when I try the more complected query, no luck. I assume it has to do with converting the mysql WHERE date = “open” into proper (escaped?) php….
I’m not sure what the procedure is when I sorta found my own problem = The biggest issue (of several). When I used the “generate PHP code” feature on myphpadmin it didn’t keep the capital “E” in Email from the name of the column in the table…
Those newline characters might be the problem…
try