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"]}\")";
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!!
I'm having a 'mare trying to get some simple data from my MySQL database.
Executing the following command in phpMyAdmin works fine:
SELECT coords FROM btDCSimpleMapMarkers WHERE bID = 152
but when I attempt the same in PHP (where bID is dynamically substituted):
echo $db->query("SELECT coords FROM btDCSimpleMapMarkers WHERE bID = {$bID}");
I get this:
"coords
"
"coords
"55.8858884,-3.5473646","56.1962574,-4.7451167","58.1476532,-5.2027190","55.9714768,-3.1769557","57.6809791,-4.3305414","55.9409414,-3.5107965","56.2444546,-4.2167933","55.5162577,-4.3799082","57.1417936,-2.0930123","55.9699585,-3.1853694","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","55.6459257,-3.1714130","55.8614198,-3.0658253","55.9433622,-3.0590451","55.9563443,-2.7912248","55.8533561,-4.3041345","55.2410909,-4.8555597","55.8577681,-4.2443929","55.8781498,-4.2898555","57.1426478,-2.1232869","56.8705582,-5.4453786","56.1884131,-4.4899996","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","55.9717258,-3.1931145","55.9491408,-2.7235834","55.8922571,-3.0575724","57.0761811,-2.7793013","56.1888841,-3.0137383","55.6956709,-3.3806546","57.4871048,-4.2490284","56.4125195,-5.4727019","56.0751328,-3.4419449","58.4337677,-3.0813735","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0","0,0"
"
I don't know where the extra stuff at the beginning is coming from (especially the column name). The field contains one long string, and the column type is VARCHAR(20000).
Any help would be appreciated, cos I'm stumped!
You seem to be trying to echo the mysql result directly.
What you need to do is use mysql_fetch_array() to get each row of data and then echo that.
This is how I would do it:
$sql = "SELECT coords FROM btDCSimpleMapMarkers WHERE bID = 15";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['coords'] . "<br />";
}
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
I'm sorry if this question frustrates anyone ... I am truly a beginner to PHP + MYSQL but I would love to make some progress on this one!
My Goal:
To create a table that I can view in a web page.
To be able to add data (rows) to this table and still have the data be there the next time the page is loaded.
Step 1: Creating the table
<html>
<body>
<?php
// Conect to MYSQL
$con = mysql_connect("localhost", "My_Username", "My_Password") or die(mysql_error());
echo "Connected to MYSQL </br>";
mysql_select_db("My_Database") or die(mysql_error());
echo "Connected to Database";
// Create a MySQL table in the selected database (called ExampleTable)
$sql = "CREATE TABLE ExampleTable
(
// Set the primary key (personID)
personID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(personID),
ColumnOne varchar(15)
ColumnTwo varchar(15)
ColumnThree varChar(30)
)";
// Execute query
mysql_query($sql,$con);
mysql_query("INSERT INTO ExampleTable(ColumnOne, ColumnTwo, ColumnThree)
VALUES ('Data1', 'Data2', 'Data3')");
mysql_query("INSERT INTO ExampleTable(ColumnOne, ColumnTwo, ColumnThree)
VALUES ('Data_Data1', 'Data_Data2', 'Data_Data3')");
mysql_close($con);
?>
</body>
</html>
So, I have now created a MYSQL table with two three columns, and two rows of data. How can I get this table to show up on a web page?
Step 2: Saving / Retrieving saved data
Is there some way that I can add data to a table, so that the data will be there permanently? - or is this how it works by default?
For example: Let's say that I have a form with a button on it. When the button is clicked a new row is added to the table 'ExampleTable'. The next time the user visits the page the table will be updated with his newly added data.
Thank you very much for any help. I understand that I am a beginner and do not fully understand these topics yet. Any responses will be greatly appreciated.
I'd recommend creating the table in a separate step, not from PHP; you don't want every time your web page is refreshed to create a new table.
Once your table is created, you can get the data from it by executing (within your PHP, using mysql_query) a query like "SELECT * from {tablename}". Once you've got that query result from mysql, then you can use the various PHP looping and mysql record reading methods to output the results from your query in the form you want into the page your PHP script will be serving to your client.
There are SELECT and UPDATE queries to do this. For example if you want to show data in a table, you would use query looking like this:
SELECT * FROM ExampleTable
In PHP, you can work with these data for example like this:
$query = mysql_query("SELECT * FROM ExampleTable");
while ($row = mysql_fetch_array($query)) {
echo $row["ColumnOne"];
}
And to the UPDATE query:
UPDATE ExampleTable SET ColumnOne = 'some value'
Usage in PHP is also with mysql_query. You can also use WHERE conditions in the query.
1 - Displaying All Data
<?php
// Conect to MYSQL
$con = mysql_connect("localhost", "My_Username", "My_Password") or die(mysql_error());
echo "Connected to MYSQL </br>";
mysql_select_db("My_Database") or die(mysql_error());
echo "Connected to Database";
// Get all the data from the "ExampleTable" table
$result = mysql_query("SELECT * FROM ExampleTable") or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>ColumnOne</th> <th>CoumnTwo</th> <th>CoumnThree</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['ColumnOne'];
echo "</td><td>";
echo $row['ColumnTwo'];
echo "</td><td>";
echo $row['ColumnThree'];
echo "</td></tr>";
}
echo "</table>";
?>
From: http://www.tizag.com/mysqlTutorial/mysqlselect.php
2 - Data Storage
Anything INSERT-ed into a database will remain* in the database until it is explicitly deleted.
*with few exceptions - but you'll learn about them a little later in your database journey :)