I have a simple <ul> where you can add a list item with an input field:
$('#plannerform').submit(function(e) {
var val = $(this).find('#plannername').val();
$('ul.plannerlist:visible').append('<li>' + val + '</li>');
e.preventDefault();
});
My question is: Is it possible in a way to save this created list on a mySQL database on a webserver? I haven't got much experience in PHP or other languages for server sided storage. And if it's possible, can you tell me any links where it's explained how? I spent some time already with searching, but I didn't find anything because I simply don't know what to search after.
Here is a simple php script that I wrote to connect to my MySQL DB, and retrieve along with display each result in a given column.
Just replace:
Hostname with probably your local IP if MySQL is installed on your local machine.
Your MySQL username, probably root if you haven't created another user.
The password, which could be blank if you didn't create one.
Database with the name of your Database.
<?php
//Connect to DB
$conn = new mysqli("Hostname","Username","Password","Database");
//If the connection has errors
if ($conn->connect_error){
//Display the error
die("Connection failed because: " . $conn->connect_error);
}
//Otherwise the connection is good so lets create a sql query
$sql = "SELECT * FROM Database";
//Get the results of the query
$result = $conn->query($sql);
//If the results have rows
if($result->num_rows > 0){
//While there are more rows in the results
while($row = $result->fetch_assoc()) {
//Display in HTML paragraph form: Column1 = DataInColumn1
echo '<p> Column1 = ' . $row["Column1"] . ' </p>';
}//End While
}//End If
//Otherwise the query had no results
else{
echo '<p>No results found!</p>';
}
?>
Related
Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}
I have a web page created in php using html code. I want to save user information entered in my web page to a MySQL database. I am using php as the middle man to link the frontend web page(htmnl code) to the database(mysql).
Inside my link folder (middle man php file) I have the following:
<?php
//Gets server connection credentials stored in serConCred2.php
require_once('ConCred2.php');
//SQL code for connection w/ error control
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$con){
die('Could not connect: ' . mysqli_connect_error());
}
//Selection of the databse w/ error control
$db_selected = mysqli_select_db($con, DB_NAME);
if(!$db_selected){
die('Can not use ' . DB_NAME . ': ' . mysqli_error($con));
}
//Co-PI and Co-Investigator Information variables
$Co_FNAME = $_POST['fname'];
$Co_LNAME = $_POST['lname'];
$Co_SLNAME = $_POST['slname'];
$Co_DEGREE = $_POST['Degree_Selection'];
$Co_DEGREE_Other = $_POST['other_specify_degree']; //hold the value of degree if user selected other from the dropdown menu
$Co_CPOS = $_POST['Current_Position_Selection'];
$Co_CPOS_Other = $_POST['other_specify_cpos']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_INST = $_POST['Institution_Selection'];
$Co_INST_Other = $_POST['other_specify_inst']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_SCHOOL = $_POST['School_Selection'];
$Co_SCHOOL_Other = $_POST['other_specify_school']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_DEPART = $_POST['Department_Selection']; //Este se estara eliminando en la version online
$Co_DEPART_Other = $_POST['other_specify_department']; //hold the value of Department if user selected other from the dropdown menu
$Co_PROGRAM = $_POST['program'];
$Co_EMAIL = $_POST['email'];
$Co_PHONE = $_POST['phone'];
//If decition when user select other from the dropdown menu
if($Co_DEGREE == "other_degree") $Co_DEGREE = $Co_DEGREE_Other;
if($Co_CPOS == "other_cpos") $Co_CPOS = $Co_CPOS_Other;
if($Co_INST == "other_inst") $Co_INST = $Co_INST_Other;
if($Co_SCHOOL == "other_school") $Co_SCHOOL = $Co_SCHOOL_Other;
if($Co_DEPART_Other == "other_department") $Co_DEPART = $Co_DEPART_Other;
//This sets a starting point in the rollback process in case of errors along the code
$success = true; //Flag to determine success of transaction
//start transaction
echo "<br>1. Going to set autocommit to 0";
$command = "SET AUTOCOMMIT = 0";
echo "<br>2. Autocomint has been set to 0";
echo "<br>3. Going to run query to see if result is true or false";
$result = mysqli_query($con, $command);
echo "<br>4. Finished running the query. Result is:" . $result;
echo "<br>5. Going to set command to BEGIN";
$command = "BEGIN";
echo "<br>6. Command is now BEGIN";
echo "<br>7. Going to run query for command BEGIN";
$result = mysqli_query($con, $command);
echo "<br>8. Query runned for command BEGIN";
echo "<br>9. Result value is: " . $result;
//Saves Pi values into database
/**
$sqlCoPI = "INSERT INTO co_pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
echo "<br>10. Going to write sql command to populate table pi_table";
/**
$sqlPi = "INSERT INTO pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
$sqlPi = "INSERT INTO pi_table (Fname) VALUES('$Co_FNAME')";
//Checks to see if theres an error in the pi db con
echo "<br>11. Sql command finished writting.";
echo "<br>12. Going to query the sql finished command to the database to determine value of result.";
$result = mysqli_query($con, $sqlPi);
echo "<br>13. Finished running sql command to database. Result value is: " . $result;
echo "<br>14. Going to enter if statements depending on result value";
if($result == false){
//die ('<br>Error in query to PI table: ' . mysqli_error($con));
echo "<br>15. I am inside the false statement. Success is going to be set as false. ";
$success = false;
//$success = true; //Cahnged this in order to test if values are being saved to db. Change back to false.
}
//Checks for errors or craches inside the code
// If found, execute rollback
echo "<br>16. Going to verify is success is true.";
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
//echo "<br>Tables have been saved with 0 errors.";
echo "<br><p style=\"color: red;\"Principal Investigator has been saved successfuly. <br><br>
You may now CLOSE this page and press the<br><br> \"Refresh List\" <br><br>
button to display name in dropdown menu selection.</p>";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>17. Success was determined to be false.";
echo "<br>Error! Databases could not be saved.<br>
Contact system manager to report error. <br> <br>" . mysqli_error($con);
}
echo "<br>18. Setting autocommit back to 1 again.";
$command = "SET AUTOCOMMIT = 1"; //return to autocommit
$result = mysqli_query($con, $command);
//Displays message
//echo '<br>Connection Successfully. ';
//echo '<br>Database have been saved';
//Close the sql connection to dababase
mysqli_close($con)
?>
As you can read, I am requiring users to fill out their information. Some of the information required are dropdown menu fields that user selects an option from among the presented ones.
The problem I am having is, when the above php code executes, it determines that the $result variable is false and doesn't save anything. When you execute the code, you get the following messages displayed:
1. Going to set autocommit to 0
2. Autocomint has been set to 0
3. Going to run query to see if result is true or false
4. Finished running the query. Result is:1
5. Going to set command to BEGIN
6. Command is now BEGIN
7. Going to run query for command BEGIN
8. Query runned for command BEGIN
9. Result value is: 1
10. Going to write sql command to populate table pi_table
11. Sql command finished writting.
12. Going to query the sql finished command to the database to determine value of result.
13. Finished running sql command to database. Result value is:
14. Going to enter if statements depending on result value
15. I am inside the false statement. Success is going to be set as false.
16. Going to verify is success is true.
17. Success was determined to be false.
Error! Databases could not be saved.
Contact system manager to report error.
18. Setting autocommit back to 1 again.
For security purposes I cant post the html content since it has sensitive name information nor the databases. Although I can ensure that the tables inside the database are called exactly as mentioned in the sql command line.
I HAVE FOUND THE PROBLEM!
After long debating I decided to recreate the database In which all the information was being stored. When I redirected the table in my sql command ( Instead of saving it in "pi_table" I saved it in a newly created database called "pi_table_2") and everything worked out properly.
Aparently my database got corrupted and phpMyAdmin didn't recognized that it was curropted.
For reference my database tables where in InnoDB format. What might have cause this to happen, who knows but if you ever encounter a similar problem, creating a small testing database and see if it saves. If it does, recreate the table and it might solve your issue like it solved mine.
Once again thank you a lot guys!!!!!
I am looking at the code and everything seems to be in order, could be a syntax error like a missing quotation for example:
//SQL code for connection w/ error control
$con = mysqli_connect("DB_HOST", "DB_USER", "DB_PASSWORD", "DB_NAME");
also
$db_selected = mysqli_select_db($con, "DB_NAME");
or die ("Cant select Database");
}
Hope this help.
Cheers;
Hasan
I was uploading data from my android application to a PHP file then inserting it to Mysql database, the problem i am having that i buy a new hosting plan and when i configured everything in the new hosting, i try to upload data from the application it shows only blank fields in the table, i am sure that there's no problem in the PHP or the android code, cause it was working fine and great with the old hosting.. i tried to change the encoding but same issue.
Here's the PHP file:
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not Connect:'. mysql_error());
}
mysql_select_db("TABLE",$con);
mysql_query ("INSERT INTO table (rep_desc,dateT) VALUES ('".$_REQUEST['report_Desc']."','".$_REQUEST['Date_Time']."')");
mysql_close($con);
?>
Thanks in advance
If there is any auto_increment column in table. Better check if its auto_increment flag not got uncheck.
Please also check length of database fields and data that you actually trying to insert.
Name of all request variables, columns, tables should be in proper case if it is a UNIX system.
get all the tables by something like this query ...
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
Ok, I'm following a youtube guide on how to create a very simple blogging system using PHP/MySQL as I'd like to get to learn these 2 languages a bit more. I'm creating this in my localhost, permissions set-up correctly.
The problem is, when I go onto localhost/tables.php, it comes up as white screen which it's supposed to, but it's not creating the relevant tables within the database?
Here's the code I'm using:
mysql.php
<?php
mysql_connect('localhost','username','password'); //where localhost is the host, username is the relevant username and password is the relevant password.
mysql_select_db('database'); //where database is the chosen database in which to drop the tables.
?>
tables.php
<?php
include "mysql.php";
$table = "ENTRIES";
mysql_query ("CREATE TABLE IF NOT EXISTS `$table` (`ID` INT NOT NULL AUTO_INCREMENT , PRIMARY KEY ( `id` ) )");
mysql_query ("ALTER TABLE `$table` ADD `TITLE` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `SUMMARY` TEXT NOT NULL");
mysql_query ("ALTER TABLE `$table` ADD `CONTENT` TEXT NOT NULL");
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem.
Any help would be much appreciated! Thanks.
As you have no errors run this code to show if you have created created the table ENTRIES.
<?php
include "mysql.php";
$result = mysql_query("SHOW COLUMNS FROM `ENTRIES`");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>
NOTE As you are starting with MySQL you would be advised to use PDO in place of the deprecated mysql_.
Here is a good tutorial
EDIT
Following comments the following code lists databases and tables on server(Note uses deprecated mysql_ function).
Ensure that the proper parameters replace "XXX".
<?php
$host= "localhost";
$username="XXX";
$password="XXX";
$database="XXX";
$link = mysql_connect($host,$username,$password); //where localhost is the host, username is the relevant username and password is the relevant password.
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
echo "<BR>";
}
echo "<BR>";
$result = mysql_list_tables($database);
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i), "\n";
echo "<BR>";
}
?>
Nothing is appearing in the error log which is frustrating and not helping me diagnose the problem
So your first poblem is to find out why it's not logging any errors. BTW it would also be a good idea to inject some echo / print statements to find out where it's failing.
Forget about the MySQL stuff and try:
<?php
trigger_error("Testing", E_USER_WARNING);
?>
Even though (once you've got the error reporting sorted out) you should get an error logged it will likely only contain a limited amount of information. Any time you call a mysql function, be via mysql_, mysqli or PDO, you should poll the return value and handle any error - even if it's just to echo the value to the screen.
It's saying that I haven't selected a database
Possibly the user account you are connecting as does not have permission to access the database.
I wonder whether someone can help me please.
I'm trying to put together a PHP script that takes data from an xml file and places the data in a mySQL data. I've been working on this for a few days and I'm still can't seem to get this right.
This is the code that I've managed to put together:
<?
$objDOM = new DOMDocument();
$objDOM->load("xmlfile.xml");
$Details = $objDOM->getElementsByTagName("Details");
foreach( $Details as $value )
{
$listentry = $value->getElementsByTagName("listentry");
$listentrys = $listentry->item(0)->nodeValue;
$sitetype = $value->getElementsByTagName("sitetype");
$sitetypes = $sitetype->item(0)->nodeValue;
$sitedescription = $value->getElementsByTagName("sitedescription");
$sitedescriptions = $sitedescription->item(0)->nodeValue;
$siteosgb36lat = $value->getElementsByTagName("siteosgb36lat");
$siteosgb36lats = $siteosgb36lat->item(0)->nodeValue;
$siteosgb36lon = $value->getElementsByTagName("siteosgb36lon");
$siteosgb36lons = $siteosgb36lon->item(0)->nodeValue;
//echo "$listentrys :: $sitetypes :: $sitedescriptions :: $siteosgb36lats :: $siteosgb36lons <br>";
}
require("phpfile.php");
//Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
mysql_query("INSERT IGNORE INTO scheduledsites (listentry, sitetype, sitedescription, siteosgb36lat, siteosgb36lon) VALUES('$listentrys','$sitetypes','$sitedescriptions','$siteosgb36lats','$siteosgb36lons') ")
or die(mysql_error());
echo "Data Inserted!";
?>
I can pull the data from the xml file, but it's the part of the script that sends the data to my database table that I'm having trouble with.
The script runs but only the last record is saved to the database.
I can parse the fields from the xml file without any problems and the check I'm trying to put in place is, if there is a 'listentry' number in the new data that is matched to one already in the table then I don't want that record to be added to the table, i.e. ignore it.
I just wondered whether someone could perhaps take a look at this please and let me know where I'm going wrong.
Many thanks
You are only calling mysql_query once. So it will only insert one row.
The sql needs to be inside the loop.