MYSQL - to coding a PHP query - php

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
$sql = "select email, count(*) as count from table where date=\"open\" group by email order by email";

Your $database variable is empty, and you are using that with your mysql_select_db

sql var in line 19 (includes empty lines) is missing $.
what is the value of $result ? or is there error before that ?

You could try using ' instead of `!
Also make sure that you have an active connection with your database. You're only checking IF the connection is possible, so I'm not sure if your actually keeping the connection intact.
Instead, you could do:
$connect = mysql_connect($db_host, $db_user, $db_pwd) or die(mysql_error());

Related

How to show 1 users mySQL information

So I have two pages. One shows all of the users who have filled out the form. On this page the ID is hyperlinked to the users individual page. On the individual page it should only show their individual information. When I do it, it still shows everyones information and I can't figure out how to change it.
This is my table for all the users.
<?php
//Establish the connection to the database server
$conn = mysql_connect("localhost","root", "MIS42520!$") or die (mysql_error());
//Tell the connection which database to user_error
mysql_select_db("assignment_3", $conn);
//Tell the database what you want, with an SQL statement
$sql = "select id, firstname, lastname, emailaddress from usertable";
//Run the sql statement against the connection
$result = mysql_query($sql, $conn) or die (mysql_error());
//Process the result set $result
print "<center><table id='adminTable' border=1>";
print "<tr><th>ID</th><th>First Name</th><th>Last Name</th> <th> Email Address</th> </tr>";
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['emailaddress'] . "</td></tr>";
}
echo "</table></center>"; //Close the table
?>
My table for the single user is essentially exactly the same but I added the following on top
$id= $_GET['id'];
Change your $sql variable to this:
$sql = "select id, firstname, lastname, emailaddress from usertable where id='".htmlentities($_GET['id'])."'";
Well.. you need to change the statement for the page of the only one user i think
Try this
$sql = "select id, firstname, lastname, emailaddress from usertable where id =".$id;
And as #jay-blanchard say in the comment, try not to use deprecated methods/clases, use prepared statements here's the link to themysqli class

Page hangs on multi command mysqli php

So I'm pretty new to PHP and I'm mostly just struggling my way through it but I've hit a roadblock that I just can't get over.
My goal is to run a few commands to clear and update a standings table and then display the data in a table. I've got the table to display pretty much no problem but when I add the code in to update the table the page stops before it even displays the table and it's just a blank page, it wont even run any of the HTML.
Here's the PHP, I can provide the rest of the page code if needed.
http://pastebin.com/GZ3KcNXK
<?php
$con = mysqli_connect("localhost","uakronhv_admin","uakhvzdbadmin01","uakronhv_game1");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "DELETE FROM standings WHERE 1=1; ";
$sql. = "INSERT INTO standings (`pId`,`pName`,`pStarve`) SELECT p.pId, concat(p.pFirst," ",p.pLast), TIMEDIFF(NOW(),s.lastTag) FROM players p left join starve s on p.pId = s.zId; ";
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Human" WHERE sId NOT IN (SELECT DISTINCT taggedId FROM tags); "):
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Zombie" WHERE (sId IN (SELECT DISTINCT taggedId FROM tags)) OR (sId IN (SELECT DISTINCT taggerId FROM tags)); "):
$que=$mysqli_query($sql);
$sp = mysqli_query($con,"call updateStandings()");
$result = mysqli_query($con,"SELECT * FROM standings");
echo "<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Status</th>
<th>Since Last Tag</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td style=\"text-align:center\">" . $row['pId'] . "</td>";
echo "<td>" . $row['pName'] . "</td>";
echo "<td style=\"text-align:center\">" . $row['pStatus'] . "</td>";
if ($row['pStarve'] > '72:00:00')
echo "<td style=\"text-align:center\">Starved</td>";
else if
(is_null($row['pStarve']))
echo "<td style=\"text-align:center\">--</td>";
else
echo "<td >" . $row['pStarve'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I'm just going to point out where the faults are, which may very well fix your code. If it doesn't, then you will need to read up on the better tutorials.
Regarding this code block:
$sql. = "INSERT INTO standings (`pId`,`pName`,`pStarve`) SELECT p.pId, concat(p.pFirst," ",p.pLast), TIMEDIFF(NOW(),s.lastTag) FROM players p left join starve s on p.pId = s.zId; ";
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Human" WHERE sId NOT IN (SELECT DISTINCT taggedId FROM tags); "):
$sql.= $mysqli_real_escape_string("UPDATE standings SET sStatus = "Zombie" WHERE (sId IN (SELECT DISTINCT taggedId FROM tags)) OR (sId IN (SELECT DISTINCT taggerId FROM tags)); "):
$que=$mysqli_query($sql);
The concatenation is incorrect $sql. = those should read as $sql .= which is why you say that the DELETE part works but not the rest following that statement. Had you used or die(mysqli_error($con)) to mysqli_query() it would have signaled the error.
Then you're probably wanting to sanitize input using mysqli_real_escape_string() but that's not how that function works and you don't use a $ sign in front of that function.
It works like this:
$variable = mysqli_real_escape_string($con, $_POST['variable']);
Read up on the function:
http://php.net/manual/en/mysqli.real-escape-string.php
Then you're using $mysqli_query with a dollar sign in front of that function, it's just mysqli_query.
Then you're doing SET sStatus = "Human" that should be single quotes and not double quotes SET sStatus = 'Human' and do the same for the other one.
Having used error reporting and checking for DB error using/adding or die(mysqli_error($con)) to mysqli_query() would have signaled the errors.
Error reporting should have given you warnings such as Undefined variable... in regards to $mysqli_query and $mysqli_real_escape_string.
That should give you enough information to debug your code.
Blank page often means syntax error. Maybe it's the one in front of the INSERT statement?
$sql. = "INSERT INTO standings ...";
Try this one ;)
$sql .= "INSERT INTO standings ...";
Edit: And as mentioned in the comments, it's the first step in debugging. Forgot to say it directly.

Need help for PHP function that creates html table column with buttons for updating sqlite table

That's the function which I'm using to print the contents of 'username' table:
function showtable()
{
ob_start();
$db = new PDO("sqlite:test.db");
$query = "SELECT * FROM " . $_SESSION['username'] . " ORDER BY `a` DESC;";
$result = $db->prepare($query);
$result = $db->query($query);
print "<table>";
print "<tr><td>First Column</td><td>Second Column</td><td>Third column</td></tr>";
foreach ($result as $row)
{
print "<tr><td>" . $row['a'] . "</td><td>" . $row['b'] . "</td><td>Here stays the button</td></tr>";
}
print "</table>";
unset($db);
ob_end_flush();
}
So, how should look a function so when creating each row of the html table, a button for updating the corresponding sqlite table row is inserted in the third cell (named 'Here stays the button' for easier reading)? I'm calling my function when opening the test.php (with added required_once('functions.php')) file in main browser window, nothing special in that.
That's the UPDATE query:
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = " . $row['a'] . ";";
a column is integer primary key
b column is text
c column is integer, all fields hold 0 value
P.S. Don't talk about AJAX, I'm not ready for it (and don't like it, a lot of pages that use AJAX lag the browser). Just asking for ideas about a simple php function, that adds UPDATE TABLE functionality through buttons for each row.
Thanks in advance :)
What is the updating for? what will happen if C = 1?
anyway for your question, my suggestion is to use an anchor tag.
i.e
in the "Here stays the button" will be Update
in your test.php
if($_GET['a_new'] != '')
{
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = ".$_GET['a_new']."";
}
p.s you have excess ";" in your query. you only add the query on the end of the query statement not inside it i.e $sql = "select * from"; not $sql = "select * from;";

html table not being populated from MySQL table

I am adapting some scripts that I found through Google that monitor users who login in to a website.
This consists of including this in each page I want to monitor:
<?
include_once("config.php");
include_once("functions.php");
?>
config.php looks like this (I have removed info on actual database):
<?php
DEFINE ('DB_USER', '');// database username
DEFINE ('DB_PASSWORD', '');//database password
DEFINE ('DB_HOST', '');//database host, usually localhost
DEFINE ('DB_NAME', '');//and finally the database name
$dbc = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error());
#mysql_select_db (DB_NAME) OR die('Could not select the database: ' . mysql_error() );
?>
functions.php looks like this:
<?php
$page = $_SERVER['PHP_SELF'];
$user = $_SESSION["name"];
$logq = "INSERT INTO logs (Name, Page, Date) VALUES ('$user', '$page', NOW())";
$logr = #mysql_query($logq);
?>
This works fine, i.e. the table in my database is populated correctly.
However the file that is supposed to generate a table on a webpage to show the information in the MySQL table isn't working. The file, logs.php, looks like this:
<?php
$lq = "SELECT id, Name, Page, DATE_FORMAT(date, '%d %M, %Y') as sd FROM logs ORDER BY id DESC LIMIT 50";
$lr = #mysql_query($lq);
if($lr){
echo "<table><th>Name</th><th>Page</th><th>Date</th>";
while($lf = mysql_fetch_array($lr, MYSQL_ASSOC)){
echo "<tr><td>" . $lf['Name'] . "</td><td>" . $lf['Page'] . "</td><td>" . $lf['sd'] . "</td></tr>";
}
echo "</table>";
}
else
{
echo "No results!";
}
?>
Even though there is data in the MySQL table I am always getting just 'No results!' showing when I browse to the page.
Can anyone see what the problem is?
Perhaps you don't have a db connection in logs.php? If your code is the full file then this should be the problem.
If so, just include config.php at the top of the page.
One thing I can see in your query is that date is a reserved word.
You need to wrap that in backticks:
"SELECT id, Name, Page, DATE_FORMAT(`date`, '%d %M, %Y')....
or rename the column.
This is probably throwing an error in your query that you are not seeing despite the trigger_error() recommendation: Error reporting is probably turned off on your server. This is the right behaviour in a production environment, because you don't want the user to see error messages. While developing however, you can activate error reporting to see what's wrong.
try do it like this
$query = "SELECT * FROM logs ORDER BY id DESC LIMIT 50";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
echo "<table><th>Name</th><th>Page</th><th>Date</th>";
echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['Page'] . "</td><td>" . $row['sd'] . "</td></tr>";
echo "</table>";
}
hope it helps

MYSQL/PHP outputting entire table when I only want to output one row

This is definitely a beginner's question. There are two issues. The id in my MYSQL table (set to autoincrement) keeps going up, even though I delete rows from my table (I'm using phpmyadmin). As for the other issue, I can't seem to find a way to work with the row most recently entered by the user. The code echos all existing rows from MYSQL.
I've bolded the most pertinent section of code.
<?php
//establish connection to mysql
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
/*retrieve user input from input form
and initialize variables */
$Word1 = $_POST["Word1"];
$Word2 = $_POST["Word2"];
$Word3 = $_POST["Word3"];
$Word4 = $_POST["Word4"];
$Word5 = $_POST["Word5"];
//select db
mysql_select_db("madlibs", $con);
//insert user input for word 1
$sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES
('$Word1', '$Word2', '$Word3', '$Word4', '$Word5')";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query ("SELECT * FROM test");
/* take note here */
while($row = mysql_fetch_array($result))
{
echo $row['Word1'] . " " . $row['Word2'] . " " . $row['Word3'] . " " .
$row['Word4'] . " " . $row['Word5'] . " " . $row['id'];
echo "<br />";
} /* take note here */
mysql_close($con);
?>
$result = mysql_query ("SELECT * FROM test order by id desc limit 1");
As for your id question...that's how ids work. They don't fill in gaps.
On a side note: Never ever put user submitted data directly into the query string. Always escape them with mysql_real_escape_string().
SELECT * FROM test ORDER BY Id DESC LIMIT 1

Categories