Page hangs on multi command mysqli php - 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.

Related

sql works on phpmyadmin but not on php script

I have 2 table names courses and institution.
Here is my query:
CREATE TEMPORARY TABLE
IF NOT EXISTS temp AS (SELECT course_name, ins_name
FROM courses
where course_name='ACCA') ;
select institution.ins_name, address, contact, website,
email from institution join temp on institution.ins_name = temp.ins_name
And here is my php script:
<?php
session_start();
include('db_connect.php');
$sql="CREATE TEMPORARY TABLE
IF NOT EXISTS temp AS (SELECT course_name, ins_name
FROM courses
where course_name='ACCA') ;
select institution.ins_name, address, contact, website, email from institution join temp on institution.ins_name = temp.ins_name";
$result= mysqli_query($conn, $sql) or die("MySQL error: " . mysqli_error($conn));
while ($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['ins_name'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['contact'] . "</td>";
echo "<td>" . $row['website'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>"
?>
I can't figure out what the problem is. The error i get is:
MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select institution.ins_name, address, contact, website, email from institution j' at line 6
What am i doing wrong?
From Multiple Statements:
MySQL optionally allows having multiple statements in one statement
string. Sending multiple statements at once reduces client-server
round trips but requires special handling.
Multiple statements or multi queries must be executed with
mysqli_multi_query(). The individual statements of the statement
string are separated by semicolon. Then, all result sets returned by
the executed statements must be fetched.
Alternatively, just fire two queries.
Every query must be executed separately. create and select are two different queries so first you need to call mysqli_query for create and then mysqli_query for select
You need alias on each column :
select institution.ins_name, institution.address, institution.contact, institution.website, institution.email from institution join temp on institution.ins_name = temp.ins_name";

PHP, MySQL - JOINs

I am new to PHP and I just cannot figure out my code. I am using MySQL and PHP.
table: person
PK: personID
Other fields: lastName, firstName, hireDate, imgName
table: validMajors
PK: majorAbbrev
Other Fields: majorDesc
(Junction) table: personMajors
personID, majorAbbrev
When I run my code (using NATURAL JOIN) it will display the image, last&first name, and hire date. Which is great! But I need it to display their majors as well (I would like the majorAbbrev to be displayed). It also does not display people who are in the person table but are not in the personMajors table, which is an issue because we have staff members in the person table (who do not have a major since they are not a student)
Here is my code:
<table align="center">
<?php
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
if ( mysqli_connect_errno() ) {
die( mysqli_connect_error() );
}
$sql = "SELECT * FROM person NATURAL JOIN personMajors ORDER BY lastName";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
$columns=4;
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if($i % $columns ==0){
echo "<tr>";
}
echo "<td class='staffImage badgeText frameImage displayInLine'>" . "<img src='images/staff/".$row['imgName'].".jpg'>". "<br>".
"<strong>" . $row['firstName'] . "</strong>" ." ".
"<strong>" . $row['lastName'] . "</strong>" . "<br>" .
"Hire Date: ".$row['hireDate'] ."</td>";
"Major: " .$row['majorAbbrev'] ."</td>"; //Does not display
if($i % $columns == ($columns - 1)){
echo "</tr>";
}
$i++;
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</table>
Any ideas/solution will be greatly appreciated!
Because you are not concatenating your php properly. You ended (;) your echo after displaying the $row["lastName"].
You can try these to join the three tables:
SELECT * FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Or you can define what columns to call in your query:
SELECT person.personID,
person.lastName,
person.firstName,
person.hireDate,
person.imgName,
validMajors.majorAbbrev,
validMajors.majorDesc
FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Then you can call the results with the way you are calling it right now (cleaner version):
echo '<td class="staffImage badgeText frameImage displayInLine">
<img src="images/staff/'.$row["imgName"].'.jpg"><br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>
Hire Date: '.$row["hireDate"].'
Major: '.$row["majorAbbrev"].'
</td>';
(Second try): Is the person to major relationship one to one or one to many?
OK, this SELECT Statement should work:
SELECT person.*, validMajors.* FROM person AS p, validMajors AS vm, personMajors AS pm WHERE p.personID = pm.personID AND pm.majorAbbrev = vm.majorAbbrev

Mysqli Multi Query Or A better Alternative

I have an appointment database and I can successfully print the data. What I want to do now is limit the appointments that are shown to the result from query 1.
I currently get two errors the first one is unexpected query and the other error is Fatal error: Function name must be a string. How would i rewite it so that both queries work? or an alternative better way to get this working
<?php
//MySqli Databse Connection
require "id.php";
require "calendarconnect.php";
//MySqli Select Query 1
$lep = $mysqli->query("SELECT lep FROM appointments WHERE ID = $contactid");
$line = mysqli_fetch_array($query1, MYSQL_ASSOC);
//MySqli Select Query 2
$query = $mysqli->query("SELECT ID, appointment, nature, doctorname, lep FROM appointments WHERE lep = $line ORDER BY appointment");
print '<table cellpadding="10" cellspacing="3" border="1" class="sortable">';
print '<tr><th>Date/Time</th><th>Nature</th><th>Doctor Name</th><th>Actions</th></tr>';
while($row = $query->fetch_assoc()) {
print '<tr>';
print "<td>" . date('m-d-y g:i A', strtotime($row['appointment'])) . "</td>";
print '<td>'.$row["nature"].'</td>';
print '<td>'.$row["doctorname"].'</td>';
print "<td>Edit | ";
print "<a href=\"appointmentdelete.php?id=" . $row['ID'] . "\"onclick=
\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";
print '</tr>';
}
print '</table>';
require "freeclose.php";
?>
Its not necessary to do it with 2 Querys. So you not must transfer the result from Query 1 to the client to put in in the second.
Try this:
SELECT b.ID, b.appointment, b.nature, b.doctorname, b.lep
FROM appointments a
LEFT JOIN appointments b ON b.lep = a.lep
WHERE a.ID = $contactid
ORDER BY b.appointment;

MYSQL - to coding a PHP query

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());

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;";

Categories