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 :)
Related
i am trying to learn PHP and MYSQL. I have created a database in phpmyadmin which has the following attributes:
database name = my_database
table name = users
The table has:
attributes (id,Name, Password, Phone Number)
A pictorial example of what I have looks like:
The problem is I wrote a query in php that would select all the data from the table and display it using a loop. For some reason no matter how much data I add in my users table, the code always omits the first row of data and displays the rest of the users data.According to my code, the output should be each user name displayed with their id number, but the information of the first user is never shown, and the rest of the users are shown perfectly.Can someone please help me regarding this.
my code:
<?php
$counter=0;
$mysqli=mysqli_connect('localhost', 'root','','my_database');
if(mysqli_connect_errno())
{
echo'connection failed'; echo"<br>";
}
else{
echo"connection SUCCESSFUL";echo"<br>";
}
$sq1="select * from users";
//$sq1="SELECT `Name`, `Password` FROM `users` ORDER BY `id`";
$res= mysqli_query($mysqli,$sq1);
if($res)
{
echo"Database Query Successful";echo"<br>";
$user_array= mysqli_fetch_array($res);
//print_r($user_array);
while($user_array=mysqli_fetch_assoc($res))
{
$user_id=$user_array["id"];
$user_name=$user_array["Name"];
//$user_phonenumber=$user_array["Phone Number"];
echo'The user name is '.$user_name.' The id is '.$user_id;
}
}
else
{
echo"Databse unsuccessful";
}
?>
That's because you called mysqli_fetch_array before entering the loop , remove the following line:
$user_array= mysqli_fetch_array($res);
I'm trying to create a page that shows the name of multiple mysql tables and creates a link for each one. When a user clicks a link, he's taken to a page that shows him the table contents.
For example:
Link with table name.
Table name
The user clicks the link and is taken to the page contents.php. That page prints the table contents.
For example if I have a table with Name and Age columns and John and 24 inserted in the columns, the page would print John and 24.
I appreciate if anybody can help me.
It would be way easier to do this with a GET request rather than a post request.
Table name
Then in your contents.php file:
<?php
$tablename = $_GET["tableName"]
/* all your queries that you want to do with tablename goes here */
?>
try this one...
$result = mysql_query("show tables"); // run the query and assign the result to $result
while($table = mysql_fetch_array($result)) { // go through each row that was returned in $result
echo "<a href=\"content.php?tableName=".$table[0]."\" >".$table[0] . "</a><BR>"; // print the table that was returned on that row.
}
content.php...
if(isset($_GET["tableName"]))
{
$select="select *from ".$_GET["tableName"];
$result=mysql_query($select);
while($row=mysql_fetch_array($result))
{
echo $row["name"];
echo $row["age"];
}
}
I'm building a simple bug tracking tool.
When you create a new project, all the info you fill in in the form, gets stored in the database.
When you create the new project you get redirected to a unique project page.
On top of the page it shows the name of the project, but it's not the name of the project I just created, it always shows the name of the first project in the MySQL table.
How can I show the name of the project I just created?
With this query I retrieve the data from the database.
$query = "SELECT CONCAT(name)
AS name FROM projects";
$result = #mysql_query ($query)
With this I show the project name, but it always shows the name of the first record in the table.
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
It isn't yet SQL Injection prove and is far from complete... But I'm really struggling with this problem.
You need an AUTO_INCREMENT field on your table for a unique identifier (at least, you really should). Then you can do something like this:
<?php
$sql = new MySQLi('localhost', 'root', '', 'database');
$sql->query('INSERT INTO `projects` (`name`) VALUES ("Test Project");');
$projectID = $sql->insert_id; // Returns the auto_increment field value of the last insert query performed
// So this assumes you have a field in your table called "id" in this example
$res = $sql->query('SELECT CONCAT(`name`) AS `name` FROM `projects` WHERE `id` = '.$projectID.';');
if ($row = $res->fetch_assoc()) {
echo '<h5>'.$row['name'].'</h5>';
}
?>
Since you were calling for a redirect to the unique project page, you should have something like this: header("Location: project.php?id=$projectID");
Then, on project.php, you can attempt to fetch the project with the query above, only your query's WHERE clause should be something like:
'`id` = '.intval($_GET['id']).';'
Technically, you could pass all the project info along to the next page as a request or a session cookie and save yourself a query altogether. Just make sure you keep the id handy so it's easy to update the record.
Try using ORDER BY.
$query = "SELECT CONCAT(name)
AS name FROM projects ORDER BY id DESC";
This would show the most recent project (assuming you have an ID column).
However, a much better way is to have an ID variable on the page.
$query = "SELECT CONCAT(name)
AS name FROM projects WHERE id=?";
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 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