I am working on classified website in which user will post his ads to sell something. It is basically my first web project. I have problem in making self creating pages in which when user post his ad it will generate an HTML page automatically and link and little glimpse of his ad show on a proper well designed another ad page.
Here I have described my problem properly:
When user presses submit ad button an html page will be created automatically and user will be directed to that page (how to create that page)?
How to place link of ad page on the top of other previous ads those are too on self-created page dynamically?
Here is random code of inserting and displaying database on the page:
<!DOCTYPE html>
<html>
<body>
<form action="zain.php" method="post">
Topic: <input type="text" name="topic"><br />
<br />
Name: <input type="text" name="name"><br /><br />
Attendance: <input type="text" name="attendance"><br />
<br />
<input type="reset" name="reset">
<input type="submit" name="submit" value="Go">
</form>
<?php
$user = 'root';
$password = 'zz224466';
$db = 'Zain';
// Create connection
$conn = mysqli_connect('localhost', $user, $password, $db);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "";
mysqli_select_db($conn, "zain");
$insert = "INSERT INTO lectures (Topic,Name,Attendence) VALUES('$_POST[topic]','$_POST[name]','$_POST[attendance]')";
mysqli_query($conn,$insert);
///////////Write records on the Screen//////////////
$sql = "SELECT * FROM lectures";
$myData = mysqli_query($conn,$sql);
while($record=mysqli_fetch_array($myData)){
echo $record['Topic']. " "
." ". $record['Name']." ".$record['Attendence'];
echo "<br>";
}
mysqli_close($conn);
?>
</body>
</html>
Can you please show me some hints to solve my problem?
After adding lecture you can get id of record in database by function
$id = mysqli_insert_id($conn);
You can prepare new page with id on it for example:
page.com/lecture.php?id=3
Where id is your lecture id to generate. Under this site you should prepare php code to show exactly this lecture.
To redirect to new lecture page you can check this post: How to make a redirect in PHP?
Links to other ads can be easly added by changing id in url.
PS. You shouldn't put $_POST parameters directly to database, there is a possibility of SQL injection, use http://php.net/manual/en/mysqli.real-escape-string.php
As gonzalo commented, you don't need to create an html page. Rather save the details into DB and create a dynamic (.php) file; and let this file do all the work. ie. Pass on the id of the ad to that file; fetch the details from the db and present it to the user using html markup. That being said, I strongly recommend to use a framework.
If at all you want to create fresh page each time (though i too wouldn't recommend that), you can store your data into variables and create a page with fopen() and fwrite() and then add header('location:file.ext') to redirect it to that url
Related
I have a database of some entities (to warn people from them, scan fraud, etc.) and provide a search box when some one searches.
It will tell him if this entity is included in this fraud list, and why to show for an example a source of the warning if no source it won't show it
I'm so confused I can't even start, should it be just normal listing and user can just do ctrl + f... or I have to do it more creatively
First you haven't provided a structure of the database so I added some example colums like websitename, url and added_at
You first need a Database connection
$pdo = new PDO("mysql:hostname=localhost;dbname=fraud"; "mysqlusername, "mysqlpassword");
Then you need a search form
<form action="index.php?search=1" method="GET">
Search query: <input type="text" name="query"><br>
<input type="submit"><br>
</form>
After that you need to get the entries from the MySQL Database.
if(isset($_GET["search"])) {
$stmnt = $pdo->prepare("SELECT * FROM table WHERE websitename = ? OR url = ?");
$stmnt->execute(array($_GET["query"], $_GET["query"]));
// Print values
while($row = $stmnt->fetch()) {
echo $row["websitename"];
echo $row["url"];
echo $row["added_at"];
}
}
So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.
I am developing a web application where I want to restrict update or insert more than once by navigating back to referring page. Let me present you three model files in the order of flow so that I can raise the zone where I am stuck.
register.html
<html>
...
<form id="form1" name="form1" method="post" action="process.php">
<label for="textfield">Name</label>
<input type="text" name="name" id="name" />
<input type="submit" name="Submit" value="Submit" />
</form>
...
</html>
process.php
<?php
echo "Welcome ".$_GET['para'];
?>
success.php
<?php
if(isset($_POST['Submit']))
{
$name = $_POST['name'];
// some database update here ...
echo "<a href='success.php?para=$name'>Done. Click to go next</a>";
unset($_POST['Submit']);
}else{
echo "Error in submission";
}
?>
The above three files are very simple. Here the update part has nothing to do when the user hits the back button after landing on page success.php because of unset($_POST['Submit']);. But when the user goes back further by hitting the back button again it reaches register.html and can again come up with the $_POST['Submit'] set and may do the update part which is sometimes vulnerable. I know there is Post/Redirect/Get to solve this issue, but I want some other alternatives so that the part gatekeepering the update part may be made so efficient that it would not allow the same anymore by clicking the back button.
If you are getting duplicate records inserted.
You may try INSERT IGNORE
ADD UNIQUE INDEX to your table to prevent this happening
you may choose any one of INSERT IGNORE and REPLACE according to the duplicate-handling behavior
Refer https://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
Lastly you may like simple php with mysqli_num_rows()
$sql = "SELECT id FROM table-name WHERE column-name1 = ? AND column-name2 = ? ;
$mq = mysqli_query($sql);
if (mysqli_num_rows($mq) < 1) {
$sql = "UPDATE table-name SET (colum-names) VALUES (...)";
mysqli_query($sql);
else {
echo "Record already updated";
}
}
I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.
I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).