I'm using XAMPP and PHP for a basic website.
I've already done most of it apart from the Content Management part.
I have a basic form where you upload a picture and add all the details necessary. I need help with keeping the format the same, because there are currently three houses on there with prices and details that are coded in HTML.
How do I echo the details out in the similar format?
Security is not an issue, because there isn't any sensitive information being used and it's not going to be used publicly. All I need to know is how to format the details and pictures in a similar way?
I have attached pictures so that you can better understand what I need help with as well. Here is the code:
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
$housepic ="housepic";
$houseprice ="houseprice";
$housetype ="housetype";
$houseloc = "houseloc";
$housedesc = "housedesc";
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="INSERT INTO $tbl_name (picture, price, type, location, description) VALUES ('$housepic','$houseprice','$housetype','$houseloc','$housedesc')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<?php
$host="localhost";
$username="root";
$password="";
$db_name="content_management";
$tbl_name="houses";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "SELECT * FROM $tbl_name";
$result=mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) ) {
echo "<img src='" . $row['picture'] . "'>";
echo $row['price'];
echo $row['type'];
echo $row['location'];
echo $row['description'];
}
?>
<div class="housepost">
<img src="img/houses/house_01.jpg">
<h2>£350,000</h2>
<p>2 bedroom detached house for sale</p>
<p>Deanfield Avenue, Henley-on-Thames</p>
<p>Set in the heart of Henley-on-Thames and just a short walk from Henley train station is this rarely available and spacious three bedroom apartment. Offered to the market with no onward chain the property benefits from off road parking.</p>
</div>
<div class="housepost">
<img src="img/houses/house_02.jpg">
<h2>£475,000</h2>
<p>2 bedroom detached bungalow for sale</p>
<p>Fair Mile, Henley-on-Thames</p>
<p>Set in the heart of the town centre in a quiet backwater this delightful single storey detached home is rarely available and well presented.</p>
</div>
<div class="housepost">
<img src="img/houses/house_03.jpg">
<h2>£600,000</h2>
<p>3 bedroom cottage for sale</p>
<p>Remenham Row, Henley-on-Thames</p>
<p>The English Courtyard Association and The Beechcroft Trust - synonymous with the very best in retirement housing since the 1980s. An extremely attractive three-bedroom cottage with landscaped riverside gardens in this much sought after location.</p>
</div>
<?php echo '<div class="housepost">
<img>$row <img>
<h2></h2>
<p></p>
<p></p>
<p>$row</p>
</div>' ?>
</div>
I have no idea what I'm doing with PHP and I'm surprised I made it this far but I have a beginner understanding. You can see the three hardcoded HTML divs in the code, and the last div is my failed experiment attempt with PHP. If you look at the house picture, you can see the format I want the PHP script to display the information as. (Currently refreshing the page automatically creates a record with the form box titles which I need to fix as well)
Please ask questions if you need me to clarify, and if you could help me that'd be really appreciated. I'm sure the answer is super simple, it just took me a while to explain all of this.
This is the database thing I am using:
This is the format of the house in a div that I need PHP to automatically create each time a house is uploaded:
First of all I don't understand what you mean by similar format. But I guess you need to do something like this
<?php
//Remove these variables and place them in a file like config.php
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
$housepic ="housepic";
$houseprice ="houseprice";
$housetype ="housetype";
$houseloc = "houseloc";
$housedesc = "housedesc";
//Make a function with all this block like function inserhome
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Send a variable named $_REQUEST["doinsert"] from the referer page to check if to insert or not
if($_REQUEST["doinsert"] == true){
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql="INSERT INTO $tbl_name (picture, price, type, location, description) VALUES ('$housepic','$houseprice','$housetype','$houseloc','$housedesc')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
//Make a function like function selecthomes
mysql_connect($servername, $username, $password)or die("cannot connect");
mysql_select_db($db_name)or die("cannot select DB");
$sql = "SELECT * FROM $tbl_name";
$result=mysql_query($sql);
/*Change made to print all tables using mysql_fetch_assoc. I would
recommend using pdo instedof mysql_fetch_assoc functions since they are
deprecated. check http://php.net/manual/en/book.pdo.php
check the deprecation http://php.net/manual/en/function.mysql-fetch-assoc.php*/
while ( $row = mysql_fetch_assoc($result) ) { ?>
<div class="housepost">
<img src="<?php echo $row['picture'] ?>">
<h2><?php echo $row['price'] ?></h2>
<p><?php echo $row['type'] ?></p>
<p><?php echo $row['location'] ?></p>
<p><?php echo $row['description'] ?></p>
</div>
<?php } ?>
Secondly you also said:
Currently refreshing the page automatically creates a record with the
form box titles which I need to fix as well
Well it is obvious that this script will always insert a new record because each time you do an insert at the beginning of the php file, so inevitably it will insert a new record.
One thing you need to check is if the record is already inserted.
I added some functionality to demonstrate how to check to insert the record or not. It's best you should pass a variable from the url like http://mypage/inserthouse.php?doinsert=true or you can make a form from the referrer page and pass the variable from a hidden field.
You can make two buttons. One will only display the house records and the other will insert and then display the records with the newly inserted.
So the first button will link to http://mypage/inserthouse.php?doinsert=true
and the seconds http://mypage/inserthouse.php?doinsert=false or http://mypage/inserthouse.php
I suggest you should create a function for each action and check wither you need to execute an insert or not. Make the question, When should I insert a new record?
Also you will not need the variable name $tbl_name. It doesn't matter in your code and it makes the script longer.
You also need to use an include file for your variables,
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
$housepic ="housepic";
$houseprice ="houseprice";
$housetype ="housetype";
$houseloc = "houseloc";
$housedesc = "housedesc";
Your code looks like you need to read some object oriented programming for php. Give this a shot, http://www.codecademy.com/courses/web-beginner-en-bH5s3/0/1
I would also recommend using a framework instead of making it your self.
Your skills are not there yet to make your own cms. Go with MVC and Object oriented patters.
Check the zend framework it is very nice and easy to use.
I hope I helped
this is an easy and fast way to accomplish what your looking for.
i figure your problem isn't understanding PHP, DB and HTML basics, but putting it all together - so:
read the code comments CAREFULLY to understand all steps and relationships between all those 3 things.
after you get it, you can follow this link: php_file_upload to learn how to upload the picture (which is a bit more complicated, but is a good test for your learning).
this is the code (all in the same page!!!):
<!-- HTML form to add a new house -->
<form method="post">
<!-- this is only giving and existing url, notice you should change this
if you want to upload an actual pic -->
<input type="text" name="housepic">
<br>
<input type="text" name="houseprice">
<br>
<input type="text" name="housetype">
<br>
<input type="text" name="houseloc">
<br>
<input type="text" name="housedesc">
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
//init DB vars
$servername="localhost";
$username="root";
$password="";
$dbname="content_management";
$tbl_name="houses";
//conect to db
$conn = mysqli_connect($servername, $username, $password, $dbname );
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* if request method is: "post", a form was submitted.
get the submitted form params, and update DB */
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
/* notice you should add here error handling, case user didn't fill
all params */
$housepic = ( isset($_POST["housepic"]) ) ? $_POST["housepic"] : "";
$housepic = ( isset($_POST["houseprice"]) ) ? $_POST["houseprice"] : "";
$housepic = ( isset($_POST["housetype"]) ) ? $_POST["housetype"] : "";
$housepic = ( isset($_POST["houseloc"]) ) ? $_POST["houseloc"] : "";
$housepic = ( isset($_POST["housedesc"]) ) ? $_POST["housedesc"] : "";
// update DB
$sql="INSERT INTO $tbl_name (picture, price, type, location, description) VALUES ('$housepic','$houseprice','$housetype','$houseloc','$housedesc')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
/* we'll always get to this part.
notice, if a form was already submitted, we've just updated our DB
accordingly, so the houses list is already updated */
while ( $row = mysql_fetch_assoc($result) ) {
/* good practice: grab your params before,
for a nicer and reusable code */
$picture = $row['picture'];
$price = $row['price'];
$type = $row['type'];
$location = $row['location'];
$description = $row['description'];
/********************************************************************
this is the part you are asking about.
notice that echoing the HTML tags content is done
inside the WHILE loop,
which of course will be always in the same format...
*********************************************************************/
echo "
<div class=\"housepost\">
<img src=\"{$picture}\">
<h2>{$price}</h2>
<p>{$type}</p>
<p>{$location}</p>
<p>{$description}</p>
</div>";
}
/* don't forget to close your DB connection */
mysqli_close($conn);
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;
}
Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.
I'm fairly new to stack overflow. i am creating a site were you type text in to 2 text boxes and it sends it to a database. i need it then to tell me what the id of that was save it as a session and then upload it to another database. sounds confusing. but I'm stuck of one part. its viewing the result thats from just that user. i have tried just showing the the last id of the last uploaded but it can be very unreliable if multiple people are trying to upload data and know there exact session. I'm also having trouble linking the session with the id. below is the code for the forum saving to the database. I'm pretty confident with sending the id of that users inputed data to another database. I'm just stuck on finding that users inputed texts id and creating a session holding the id number
<?php
header("Location:myscorenum.php");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "score";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
session_start();
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "working";
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
}
$value = $_POST['name'];
$value1 = $_POST['description'];
$sql = "INSERT INTO all_scores (name, description) VALUES ('$value','$value1')";
if ($conn->query($sql) === TRUE) {
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
ill have the processing to inset to another database in another file. I'm confident with uploading a specific session.
any questions don't hesitate to message me. thanks for your kind help.
You can use this:
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id used in the last query
Like: echo $conn->insert_id;
Since you call it on $conn which is a mysqli instance that already has a connection, it will return your last inserted id, irregardless of other activities on the db (other queries do not affect the correctness of the output)
I edited my answer. This is the final part of your code and I've just added one line of code to it. Look if this is what you're looking for.
If this isn't working than make sure your database id field is AI.
if ($conn->query($sql) === TRUE) {
$id=$conn->insert_id; //this is where you get the last inserted id.
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
To use a session and set the ->insert_id to a session variable and use it in any other page, you can do this:
if ($conn->query($sql) === TRUE) {
session_start();
$_SESSION['id']=$conn->insert_id;
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
and now in any other page do this to retrieve the session variable:
session_start();
$id=$_SESSION['id'];
here you go and you get the id.
Are you still confused?
I have a database named hrRecords and a table named employee in that table. It has a field named contract_end. In that field, I have the contract info of the employee specifically the duration of said contract (datetime).
What I want to achieve is to check that info to see when the contract is going to come to an end and if it is display a message saying so.
I am very new to php and I tried something but I am totally lost I was wondering if I could get some guidance of some sort thank you for your support:
<?php
$employee1= mysql_real_escape($_GET["employee1"]);
$DataBase = "hrRecords";
mysql_connect("server","username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = SELECT contract_end From hrRecords
// current date being compared
if(contract_end== date(Y-m-d) {
echo "something"
}
else {
echo " employe name , Your contract will expire in x amount of days "
}
/* This is the point where everything becomes fuzzy because im thinking there has to be some other way to do this for all the employees */
fist stop using mysql it has been depreciated
use either mysqli or pdo. I will show you how to do it with mysqli
<?php
$employee1= mysql_real_escape($_GET["employee1"]); // i am not sure why you are doing this since you are not using this any where
$DataBase = "hrRecords";
$ServerName = "server";
$UserName = "username";
$Password = "password";
$mysqli = new mysqli($ServerName, $UserName, $Password,$DataBase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// since i don't know all of colum names i am making them up
$stmt= $mysqli->prepare("SELECT contract_end employe_name From hrRecords");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($contract_end, $employe_name)
while($stmt->fetch()) { // this will go thorough all of the records
// current date being compared
if($contract_end== date(Y-m-d) {
echo "something"
} else {
// you need some more code here to find x
echo " $employe name , Your contract will expire in x amount of days "
}
}
i don't know if this will help you at all. you did not have enough info for a better answer
I have been trying for two days now to figure this one out. I copied verbatim from a tutorial and I still cant insert data into a table. here is my code with form
<font face="Verdana" size="2">
<form method="post" action="Manage_cust.php" >
Customer Name
<font face="Verdana">
<input type="text" name="Company" size="50"></font>
<br>
Customer Type
<font face="Verdana">
<select name="custType" size="1">
<option>Non-Contract</option>
<option>Contract</option>
</select></font>
<br>
Contract Hours
<font face="Verdana">
<input type="text" name="contractHours" value="0"></font>
<br>
<font face="Verdana">
<input type="submit" name="dothis" value="Add Customer"></font>
</form>
</font>
<font face="Verdana" size="2">
<?php
if (isset($_POST['dothis'])) {
$con = mysql_connect ("localhost","root","password");
if (!$con){
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES
('$_POST[Company]','$_POST[custType]','$_POST[contractHours]')";
mysql_query($sql, $con);
print_r($sql);
mysql_close($con);
}
?>
This is my PHPmyadmin server info:
Server: 127.0.0.1 via TCP/IP
Software: MySQL
Software version: 5.5.27 - MySQL Community Server (GPL)
Protocol version: 10
User: root#localhost
Server charset: UTF-8 Unicode (utf8)
PLEASE tell me why this wont work. when I run the site it puts the info in and it disappears when I push the submit button, but it does not go into the table. There are no error messages that show up. HELP
I have improved a little bit in your SQL statement, stored it in an array and this is to make sure your post data are really set, else it will throw a null value. Please always sanitize your input.
in your Manage_cust.php:
<?php
if (isset($_POST['dothis']))
{
$con = mysql_connect ("localhost","root","password");
if (!$con)
{
die ("Cannot Connect: " . mysql_error());
}
mysql_select_db("averyit_net",$con);
$company = isset($_POST['Company'])?$_POST['Company']:NULL;
$custype = isset($_POST['custType'])?$_POST['custType']:NULL;
$hours = isset($_POST['contractHours'])?$_POST['contractHours']:NULL;
$sql = "INSERT INTO cust_profile(Customer_Name,
Customer_Type,
Contract_Hours)
VALUES('$company',
'$custype',
'$hours')
";
mysql_query($sql, $con);
mysql_close($con);
}
?>
First of all, don't use font tags...ever
Secondly, because of this line:
if (isset($_POST['dothis'])) {
It looks like your HTML and PHP are combined into one script? In which case, you'll need to change the action on the form to something like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Plus, you can kill a bad connection in one line:
$con = mysql_connect("localhost","root","password") or die("I died, sorry." . mysql_error() );
Check your posts with isset() and then assign values to variables.
var $company;
if(isset($_POST['Company']) {
$company = $_POST['Company'];
} else {
$company = null;
}
//so on and so forth for the other fields
Or use ternary operators
Also, using the original mysql PHP API is usually a bad choice. It's even mentioned in the PHP manual for the API
Always better to go with mysqli or PDO so let's convert that:
//your connection
$conn = mysqli_connect("localhost","username","password","averyit_net");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours)
VALUES ($company,$custType,$contractHours)";
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Assuming you set these
$stmt = mysqli_prepare($conn, $sql);
$stmt->execute();
$stmt->close();
Someone tell me if this is wrong, so I can correct it. I haven't used mysqli in a while.
Change the $sql to this:
$sql = "INSERT INTO cust_profile (Customer_Name, Customer_Type, Contract_Hours) VALUES ('".$_POST[Company]."','".$_POST[custType]."','".$_POST[contractHours]."')