How to debug PHP/SQL code that no longer works? - php

I'm new to PHP but have the code below. It essentially should load some values into an array from an SQL query then use the values in the array to output from another query. Loop within a loop.
Oddly it did work at first but now doesn't. If I separate the two queries they still work fine. So no database issues, and no error messages given. I just want to know if it's OK to use this method as it seems the easiest. Or do I have to separate the loops out?
$sql = 'SELECT menuID FROM explore_section1 WHERE menukey="sea-ovr"';
$place = $conn->query($sql);
while($row = $place->fetch_assoc()) {
$sql2 = 'SELECT url, name FROM explore_items WHERE menuID="'.$row["menuID"].'"';
$result = $conn->query($sql2);
while($row2 = $result->fetch_assoc()) {
echo '<li>'.$row2["name"].'</li>';
}
}
Thanks!

I don't see any reason for 2 queries, just that simple:
$sql = 'SELECT s.menuID, i.url, i.name
FROM explore_section1 s
LEFT JOIN explore_items i
ON s.menuID = i.menuID
WHERE s.menukey="sea-ovr"';
if($result = $conn->query($sql)) {
while($row = $result->fetch_assoc()) {
echo '<li>'.$row["name"].'</li>';
}
} else {
echo "Error:". $conn->error);
}
UPDATE Query should work: http://sqlfiddle.com/#!9/76f2f/1

OK, after hours of playing. MySQL has a weird thing. I was importing the data as nearly everywhere advises using the following structure queries:
LOAD DATA LOCAL INFILE 'C:/data.csv' INTO TABLE explore_items
FIELDS TERMINATED BY ','
ENCLOSED BY ';'
LINES TERMINATED BY '\n'
(field1, field2);
This looked to work fine and queries work if using just one table but soon as you join them they don't work. ODD!! The way I have to import the data is as per the import instructions below (found in another thread):
phpMyAdmin has the necessary tool to handle CSV import. Here are the steps to follow:
prepare the CSV file to have the fields in the same order as the MySQL table fields
remove the header row from CSV (if any), so only data is there in file
go to phpMyAdmin interface select the table in left menu
click the import button at top
browser the CSV file
select the option "CSV using LOAD DATA"
enter "," in the "fields terminated by"
enter the column names in the same order as they are in db table
click go button and you are done.
Thanks #Alex for all your time on that one!!

Related

Is there a way to call a mySQL stored procedure from PHP while passing a $_SESSION variable as its parameter?

What I'm trying to do:
I need to call a stored procedure in PHP, getStudentDevices(), stored on a mySQL server.
It takes one parameter, #p0.
I want to supply that parameter using a $_SESSION variable, studentID.
What works:
I can call the stored procedure from phpMyAdmin and it provides the correct result. So its not an issue with the procedure.
I can query the database from PHP using a different select statement, and I get the results displayed how I want, so I don't think there's an issue with connecting to the DB from PHP.
What I've tried:
This is the PHP used to fetch the results and display them in a table using the same method as mentioned previously:
I have tried using {} to pass the $_SESSION variable too.
<?php
$sql = "CALL getStudentDevices(.$_SESSION["studentID"].)";
$result = mysqli_query($conn, $sql); // $conn details omitted
// If selection is not empty
// Create table row for each record selected
if ($result->num_rows > 0) {
echo "<table> <tr> <th>DeviceID</th> <th>DeviceName</th> </tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr> <td>".$row["DeviceID"]."</td> <td>".$row["DeviceName"]."</td> </tr>";
}
echo "</table>";
} else {
// If select is empty then
echo "0 results";
}
$conn->close();
?>
Here is the stored procedure (which works perfectly when called from the DBMS):
DELIMITER $$
CREATE DEFINER=`username`#`hostname` PROCEDURE `getStudentDevices`(IN `StudentID` VARCHAR(11))
READS SQL DATA
SELECT Devices.DeviceID, Devices.DeviceName FROM Accounts
LEFT JOIN Courses ON Accounts.CourseID = Courses.CourseID
LEFT JOIN Course_Category cc ON Courses.CourseID = cc.CourseID
LEFT JOIN Categories ON cc.Category = Categories.Category
LEFT JOIN Devices ON Categories.Category = Devices.Category
WHERE Accounts.StudentID = #p0 AND Devices.Available = 1$$
DELIMITER ;
The table creation method works when using a select statement ,however, when I try to open this page using the stored procedure, nothing is displayed. The entire page is blank. Please note that security is not a concern.
The problem is how you build your query, you are mixing up the string building styles.
And you are missing quotes for the parameter
The old school style:
$sql = 'CALL getStudentDevices("' . $_SESSION["studentID"] . '")';
Variable passing:
$sql = "CALL getStudentDevices(\"{$_SESSION["studentID"]}\")";

PHP select query not getting updated records

I am working on a php form using POST and use dynamic HTML tables. I truncate the DB table every time before inserting the data in to the table which seems fine.
Select query when the page loads (to update UI part)
$query = 'SELECT * FROM TABLENAME';
$result = mysqli_query($dbConnection, $query);
$rows = array();
if(!$result)
{
//log error
}
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
print_r( $row);
$rows[] = $row;
}
}
Insert part
if(isset($_POST['u']))
{
foreach($_POST['u'] as $key => $value)
{
$ky = $_POST['x'][$key];
$query = "INSERT INTO TABLENAME (ID,KY) VALUES ($value, '$ky')";
$result = mysqli_query($dbConnection, $query);
}
}
However, upon posting, when using select query, it seems to not get the latest records inserted, I made sure to check the records are inserted properly in PhpMyadmin.
When I reload the page, it works fine. Only thing is it's not getting the updated records when it's POSTed, but works the subsequent times.
I thought it could be due to connection object and tried to use different connections objects with no luck.
INFO: Not sure if it has any impact, the database is a wordpress and I created new table in this database for this.
Thanks in advance...
The problem is that you need to do a SELECT query after your INSERT query in order to get the full data set.
You might consider posting to a separate page, and then redirect the user back to the original page after the INSERT. This will cause the SELECT to run again, since the page reloads.

MySqli not rolling back appropriately

I have a database listed as $db under mysqli. This database is contains into two tables, I listed them below as table and table2 (just for this example). Table2's rows requires an id from table. This is fine, but there might be a problem adding the columns into table2 thus requiring a rollback routine. However, it doesn't seem to be working.
I started with turning off the auto-commit. I then tried to put in the rollback command even though I am using the die command to signal a failure. As far as I am concerned the transaction could be blasted into oblivion in mid operation and the database should still be stable. So I am not sure what is going on here unless the database is completely ignoring the fact that I am trying to turn off auto-commit.
The basic structure of my code is listed below:
function problem($str)
{
global $db;
mysqli_rollback($db);
die($str);
}
mysqli_autocommit($db,false);
//Basic check if exists
$sqlstr = "SELECT * FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (mysqli_num_rows($r)>0){problem("A row already exists under that id");}
//Insert the row
$sqlstr = "INSERT INTO table (name,v1,v2,v3) VALUES ('$name','$v1','$v2','$v3');";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not insert into the table. $sqlstr");}
//Get the generated id part 1
$sqlstr = "SELECT id FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not add into the table. $sqlstr");}
//Get the generated id part 2
$row = mysqli_fetch_assoc($r);
$eid = $row['id'];
//A simple loop
$count = count($questions);
for ($i=1;i<=$count;$i++)
{
//This is where it typically could die.
$r = mysqli_query($db,"INSERT INTO table2 VALUES (...);");
if (!$r){problem("Could not add to the table2. $sqlstr");}
}
mysqli_commit($db);
Is there something I am missing? I tried to follow the examples I found for the auto-commit as closely as I could.
Transactions only work if the table engine supports them, e.g. InnoDB.

Why is this PHP-MySQL code not working properly?

It was working before and maybe someone made changes to the code and I cant detect the problem after much debugging so hopefully someone can help.
I have an html form that lets a user choose a set of option and then on form submit, POSTS these options in an array which works perfectly fine. Then I am writing the elements of an array to a MySQL table and this is where the problem occurs. My code was working fine before but now its all weird. The outputs mix up for some reason.
Below is the array values passed and then the output below the arrays.
Here is my code that writes the array values to MySQL:
error_reporting(-1);
$arr=$_POST["itemsToAdd"];
$cal=$_POST["calendar"];
print_r($arr);
// Make a MySQL Connection
//empty table first to remove any previous old on-calls stored.
$query = "truncate table ProdOnCallSetup";
if(mysql_query($query)){
}
else{
}
foreach ($arr as &$value) {
// Insert a row of information into the table "ProdOnCallSetup"
mysql_query("INSERT INTO ProdOnCallSetup
(Email) VALUES('$value') ")
or die(mysql_error());
}
Here is the code giving the output or displaying the rows in MySQL:
<ol class=”list_style”>
<?php
//make MySQL connection
$query = "SELECT * FROM ProdOnCallSetup";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<li>".$row['Email']."</li>";
echo "<br />";
}
?>
</ol>
See the problem here? Even though I write them in the correct order in MySQL when I display them the order mixes up. Order is Justin, Achau, Chellatamby but when I echo is out from the DB its Achau, Chellatamby, Justin
Unless you specifically use an ORDER BY clause in your SELECT statement, the order in which rows are returned is indeterminate and may change.... it doesn't matter what order you added the records in, this is irrelevant... use ORDER BY...
SELECT * FROM ProdOnCallSetup ORDER BY Email
(or whatever column id you want to order them on)
If you want to order them in the order you added them to the database, you'll need an autoincrement column on the table, and order by that column

insert entries in multiple tables in php

I found this tutorial at tizag.com. But It is for displaying entries from different tables.
How can I do an insert?
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT family.Position, food.Meal ".
"FROM family, food ".
"WHERE family.Position = food.Position";
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['Position']. " - ". $row['Meal'];
echo "<br />";
}
?>
You mean inserting data into multiple database tables with one query?
You can't.
Read the MySQL INSERT syntax reference.
Of course you can loop over your data and e.g. insert it into various tables step by step, but without real code from your side it is hard to help.
There are a tutorial on same site: SQL Tutorial - Insert
This can also be useful: PHP MySQL Insert Into

Categories