My blog was posting originally, however, as you work on things, things break. Now I can't for the life of me figure out why nothing is happening! The categories post to the database just fine, but my posts refuse to. Heres what I have
<?php
include_once('header.php');
if(isset($_POST['title'], $_POST['contents'], $_POST['category'])){
$errors = array();
if(!empty(trim($_POST['title']))){
$title = trim($_POST['title']);
}else{
$errors[] = 'Please enter title';
}
if(!empty(trim($_POST['contents']))){
$contents = trim($_POST['contents']);
}else{
$errors[] = 'You need to supply the content';
}
if(!category_id_exists($_POST['category'])){
$errors[] = 'That category does not exist.';
}
if(strlen(trim($_POST['title']))>255){
$errors[] = 'The title cannot be longer than 255 characters.';
}
if(empty($errors)){
add_post($title, $contents, $_POST['category']);
$id = mysqli_insert_id($mysql_connect);
$header_string = 'Location: index.php?id='.$id;
header($header_string);
die();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<style>
label { display: block;}
</style>
<title>Add a Post</title>
</head>
<body>
<h1> Add a Post </h1>
<?php
if(isset($errors) && !empty($errors)){
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
}
?>
<form action="" method="post">
<div>
<label for="title"> Title </label>
<input type="text" name="title" value="<?php if(isset($_POST['title'])) echo $_POST['title']; ?>">
</div>
<div>
<label for="contents"> Contents </label>
<textarea name="contents" rows="15" cols="50"><?php if(isset($_POST['contents'])) echo $_POST['contents']; ?></textarea>
</div>
<div>
<label for="category"> Category </label>
<select name="category">
<?php
foreach(get_categories() as $category){
?>
<option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?> </option>
<?php
}
?>
</select>
</div>
<div>
<input type="submit" value="Add Post">
</div>
</form>
</body>
</html>
Inside the header.php file, I call an init.php connect to db file which also in itself, include_once all the functions for my blog (blog.php). The function that specifically is necessary is as follows...
function add_post($title, $contents, $category){
global $mysql_connect;
$title = mysqli_real_escape_string($mysql_connect, $title);
$contents = mysqli_real_escape_string($mysql_connect, $contents);
$category = (int)$category;
$result = mysqli_query($mysql_connect, "INSERT INTO posts SET cat_id = '$category', title = '$title', contents = '$contents', date_posted = NOW()");
}
I figured a fresh set of eyes could be really valuable for me right now. When I click add post, it brings me to a page titled http://localhost/blog/index.php?id=0. Therefore it's not only not registering to the database, but it's not using the categories either.
I hope I explained this okay! I've been at this for a week now.
Edit: I ran error checks and nothing posts, so I am not sure what's going on!
Edit2: Selecting categories I add, also work and list the way I want them to. Its just something happening when I go to click add post, nothing occurs. I'm assuming its in this area
if(empty($errors)){
add_post($title, $contents, $_POST['category']);
$id = mysqli_insert_id($mysql_connect);
$header_string = 'Location: index.php?id='.$id;
header($header_string);
die();
}
As with any problem, it's always a needle in a haystack! I ran code through MYSQL workbench, and found out it was my setting to a foreign key that didn't need a relationship. It's all fixed now!
SQL Error Screenshot
I think the problem is with your database table posts.
One Case is:
You need to have an AUTO_INCREMENT field (id for example) so that the function mysqli_insert_id works perfectly. And in your case the solution would be to make the id column an AUTO_INCREMENT field.
Here is a quote:
The mysqli_insert_id() function returns the ID generated by a query on
a table with a column having the AUTO_INCREMENT attribute. If the last
query wasn't an INSERT or UPDATE statement or if the modified table
does not have a column with the AUTO_INCREMENT attribute, this
function will return zero.
Related
The form is supposed to delete a customer row from the customer table by entering customer ID, but it is not doing what it is supposed to, I dont know why! When I executed the PHP file I dont get any errors.
I know it should work because I used the same code to delete information from the employee table and it worked fine.
Delete Customer Form
<!DOCTYPE html>
<head>
<?php include 'project_header.php'; ?>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<form action="customer_delete.php" method="post">
<h2> Delete a Customer</h2>
<p>Please Enter Customer Information:</p>
Customer ID: <input type="text" ID="Customer_ID"/><br>
<input type="submit" value= "Delete"/><input type="reset"/>
</form>
</body>
<?php include 'project_footer.php'; ?>
</html>
Delete Customer PHP
<!DOCTYPE html>
<html>
<?php include 'project_header.php'; ?>
<body>
<?php
include_once 'db.php';
include_once 'display.php';
#form data
$Customer_ID=$_POST['Customer_ID'];
$sql = "delete from CUSTOMERS where Customer_ID = :Customer_ID;";
$stmt = $conn->prepare($sql);
# data stored in an associative array
$data = array( 'Customer_ID' => $Customer_ID);
if($stmt->execute($data)){
$rows_affected = $stmt->rowCount();
echo "<h2>".$rows_affected." row deleted sucessfully!</h2>";
display("select Customer_ID as Customer ID FROM CUSTOMERS;");
}
else
{
echo "\nPDOStatement::errorInfo():\n";
print_r($stmt->errorInfo());
}
$stmt = null;
$conn = null;
?>
</body>
<?php include 'project_footer.php'; ?>
</html>
It seems that there is no name attribute on your text box. This is how PHP gets the POST information, so without it being set, you can't access what the user inputted. Simply change the attribute from ID to name(or just add the name attribute if id is needed) and that should fix the issue.
Customer ID: <input type="text" ID="Customer_ID"/>
In this line you need to add the "name" attribute, and that should fix the issue.
What you should do is:
Customer ID: <input type="text" ID="Customer_ID" name="Customer_ID"/>
Greetings!
first time posting on here so I apologise for any bad habits.
I recently started an online youtube tutorial on php and how to create a blog.
I ended up getting occupied with other things and have come back to try an finish what I started and 2 things have happened. 1: my tutorials have been deleted off youtube(must of been a copyrright issue) and second I've completely forgot the method used. I assume if I was a seasoned coder this would be easy to decipher but I'm having no luck after trying for days now.
This code is for the submission form for my blog. The blog is working in the sense of if I manually input my HTML into the SQL database but all I seem to get if I use this form is a refresh of the submission page with all the information gone. No information is added to the database.
Anybody have an idea?I had a good search around the site but I ran into a dead end due to my lack of knowledge on what I was actually searching for (lots of solutions regarding javascript)
All help will be appreciated.
Sincerely
SGT Noob
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit']))
if ($_POST['submit']) {
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
include_once("../admin/connection.php");
$sql = "INSERT INTO `posts` (Post_Title, Post_Content, Post_Date)
VALUES ('$title','$content','$date')";
mysqli_query($dbcon,$sql);
echo "Post has been added to the database";
}
else {
header('Location: index.php');
die();
}
?>
<html>
<div>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//cdn.ckeditor.com/4.5.9/standard/ckeditor.js"></script>
<title> Insert Post </title>
</head>
<div>
<body>
<div id= 'cmssubmissionform'>
<form action="" method="post">
<p>
<h1> Post Title</h1>
<input type="text" name= "Post_Title"/>
</p>
<h1> Post Date</h1>
<input type="text" name= "Post_Date"/>
</p>
<p>
<h1>Post Content </h1>
<textarea name="Post_Content"></textarea>
<script>
CKEDITOR.replace( 'Post_Content' );
</script>
</p>
<p>
<input type = "submit" value="submit" />
</p>
</form>
</div>
</div>
</div>
</body>
try this
in your from change to
<input type = "submit" value="submit" name="submit"/>
You forgot to put the name attribute
The php
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
include_once("../admin/connection.php");
if (isset($_SESSION['username'])) {
$username = ($_SESSION['username']);
}
else {
header('Location: ../index.php');
die();
}
if (isset($_POST['submit'])){
$title = $_POST['Post_Title'];
$content = $_POST['Post_Content'];
$date = $_POST['Post_Date'];
$sql = "INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date')";
if(mysqli_query($dbcon,$sql)){
echo "Post has been added to the database";
}else{
header('Location: index.php');
die();
}
}
?>
Note I also changed your SQL statement to
INSERT INTO `posts` (`Post_Title`, `Post_Content`, `Post_Date`)
VALUES ('$title','$content','$date
Notice the back ticks for the table fields
Replace
if (isset($_POST['submit']))
if ($_POST['submit']) {
with
if (isset($_POST['submit'])) {
and then replace
<input type = "submit" value="submit" />
with
<input type ="submit" name="submit" value="submit" />
However, at this stage I would highly suggest starting over with a different tutorial.
Also, as has been mentioned in the comments, whenever you take arguments from a user and put them into a database query, you must absolutely make sure that the strings do not manipulate the query (imagine someone wrote 0'; DROP TABLE `blog`; -- in the date field (and "blog" were the name of your blog post table). That would be quite catastrophic, wouldn't it?
So when you handle input data, either use the prepare and bind methods of the mysqli package, or pass the strings through the mysqli_real_escape_string() function first.
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character`";
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action ="handler.php" method="post">
<label for="character">SELECT A CHARACTER </label>
<select multiple name="character">
<?php while($character = mysqli_fetch_assoc($result1)){?>
<option value ="<?php echo $character['id'];?>"</option>
<?php echo $character['name'];?></option>
<?php }?>
<input type="submit" value="submit"/>
</select>
</form>
</body>
</html>
this is my index page above
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character` where id = ". $_POST ["character"];
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php while($character = mysqli_fetch_assoc($result1)){?>
<?php echo $character["name"];?><br>;
<?php echo $character["attack"];?><br> ;
<?php echo $character["defense"];?><br>;
<?php } ?>
</body>
</html>
alright here is my handler page the issue I am having is I can select multiple options in my html select on my index page but I am having a problem displaying when multiple characters are selected in my handler page. Does anyone know how to fix this specific issue? I also want the data to displayed in a table which I'm pretty sure I can figure out.
What You actually need is logical approach. You have to ask yourself a question "what You want", "what You need" and "how to do it".
So in Your case You want to compare something but You didn't actually say what exactly You need. So if You're new i can can help You that:
What You need for sure is webpage, where user can select character from a list. But what then? I don't know. You didn't specify so...:
1) Show user a select box to choose character. How to get them? Select from database. This is what You already have.
2) After user select character You need to send this data to the server. How to do it? Use <form> tag like:
<form method="post">
<select name="character">...option list...</select>
<input type="submit" value="Search">
</form>
3) Get data sent by Your form and use them to compare with... something You have.
<?php
if( isset( $_POST['character'] ) ){
// do something with this character
}
?>
4) Show user response like found or not found or something else. Pass this data into some div like:
<?php
$found = 'set this true OR false';
if( $found ){
$message = 'Found it!';
}else{
$message = 'Not_found!";
}
?>
Then in HTML write something like:
<div><?php echo isset( $message ) ? $message : ''; ?></div>
Thats it, rest is up to You. Any simple problem You will solve by searching in Google.
-------- Edit
First of all if You're using multiple select box, the name must be:
<select name="character[]" multiple>
Then Your $_POST['character'] is now an array. You can check its content by:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
Use foreach:
$ids = []; // or $ids = array(); if php version lower than 5.4
foreach( $_POST['character'] as $v ){
$ids []= (int) $v;
}
$query = 'SELECT * FROM `character` where id IN ('. implode(',', $ids) .') ';
Am creating a webpage which allows me to search for locations by county. I am trying to create an href link on my basic homepage which will call to a Php function and then display results from my Sql database.
Not sure why but when I click on the href link the homepage just goes blank, no values returned. Have been over code and database, have shown to a few friends and can't figure out what's wrong. Any help appreciated!
This is my index.php main homepage code (with href about halfway down)
<!DOCTYPE HTML>
<?php
include("includes/db.php");
include("getAntrim.php");
include("functions/functions.php");
?>
<html>
<head>
<link rel = "stylesheet" href="styles/styles.css" media = "all"/>
<title>Location Scout</title>
</head>
<body>
<!-- Main container starts -->
<div class ="main_wrapper">
<div id="form">
<form method="get" action="results.php" enctype="multipart/form-data">
<input type="text" name="user_query" placeholder="Search for location"?>
<input type="submit" name="search" value="search"/>
</form>
</div>
<div class ="content_wrapper">
<div id ="left_sidebar">
<div id="sidebar_title">Search by County</div>
Antrim<br></br>
<div id ="content_area">
<div id ="products_box">
<!-- THIS IS WHERE FETCHED DATABASE INFO WILL GO -->
<?php
getAntrim();
?>
</div>
</div>
</div>
<!-- Main container ENDS -->
</div>
</div>
</body>
</html>
This is my getAntrim.php function, which should sort through sql database and then return stated values.
<?php
include ("includes/db.php");
if (isset ($_GET['getAntrim'])) {
$get_loc_co = "select * from locations where county='Antrim'";
$run_loc_co = mysqli_query($db, $get_loc_co); //Gets data from db and presents on main page
$count = mysqli_num_rows($run_loc_co);
if ($count==0) {
echo "<h2>No locations found in this category.";
}//if
while ($row_loc_co=mysqli_fetch_array($run_loc_co)) {
//variable to store values
$loc_id = $row_locations['loc_id'];
$loc_name = $row_locations['loc_name'];
$town = $row_locations['town'];
$county = $row_locations['county'];
$productions = $row_locations['productions'];
$disabled = $row_locations['dis_access'];
$parking = $row_locations['parking'];
$visitor = $row_locations['vis_facs'];
$transport = $row_locations['public_trans'];
$cost = $row_locations['cost'];
$accom = $row_locations['accom'];
$latitude = $row_locations['latitude'];
$longitude = $row_locations['longitude'];
$description = $row_locations['loc_desc'];
$keyword = $row_locations['loc_keyword'];
$loc_image = $row_locations['loc_img'];
echo "
<div id= 'single_location'>
<h3>$loc_name</h3>
<img src = 'Admin_area/location_images/$loc_image' width='180' height = '180'/><br>
<p><b>Productions: $productions </b></p>
<p><b>Description: $description </b></p>
</div>
";
}//while
}//if
?>
Am first time poster, so hopefully have posted this ok! Any advice appreciated.
you're checking for a query parameter, which you're NOT passing in:
Antrim<br></br>
if (isset ($_GET['getAntrim'])) {
^^^^^^^^^
$_GET contains url query parameters, e.g. example.com?foo=bar (the foo=bar portion). Since you have NO query parameters in your href, the isset() properly returns false, and your entire db code section is simply ignored.
You probably want
Antrim<br></br>
^^^^^^^^^^
to make this work as-is.
OK, so here's my code. (I'll sanitize it later. Don't worry about it.)
gallery_upload_new.php
// Check if user wants to upload to existing or new album
if (isset($_POST['album'])) {
if ($_POST['album'] == '') {
$_POST['album'] = $_POST['new_album'];
}
}
// Populate album dropdown menu
$albums = $database->query("SELECT DISTINCT(album) FROM images")->fetchAll(PDO::FETCH_COLUMN);
// Load the 'upload new photo' interface if user's not uploading it already
if (!isset($_FILES['image_link']) || !isset($_POST['caption']) || $_POST['caption'] == '') {
//var_dump($_FILES);
//var_dump($_POST);
include('views/gallery_upload_new.php');
// Otherwise store the image file, register it into database, and put the user back in the list of photos
} else {
$new_image = new Image($_POST['caption'], $_POST['album']);
$new_image->register($_FILES['image_link']['tmp_name'], $_FILES['image_link']['name']);
header('location: gallery_management.php');
}
?>
views/gallery_upload_new.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $site_title; ?></title>
<?php include('views/header.php'); //Just the global CSS and JavaScript ?>
</head>
<body>
<?php include('views/nav_menu.php'); //Site navigation panel ?>
<div id="content">
<h1>Upload new photo</h1>
<form enctype="multipart/form-data" action="gallery_upload_new.php" method="post">
<p>
<strong>Upload to album: </strong>
<select name="album">
<?php
foreach($albums as $album_name) {
echo "<option value='$album_name'>$album_name</option>";
}
?>
<option id="selectNewAlbum" value="" selected>New album</option> <input type="text" placeholder="New album name" name="new_album" id="newAlbumName">
</select>
</p>
<p><strong>Photo caption</strong> <input type="text" name="caption"></p>
<p><strong>Photo file: </strong><input type="file" required name="image_link"></p>
<input type="submit" value="Unggah">
</form>
</div>
</body>
</html>
Here's the weird part: without those two var_dump's up there, the else block won't execute. I've made sure the indexes in the $_POST and $_FILES are correct. Yet without those dummy dumps, this thing won't work. It'd just load the views/gallery_upload_new.php no matter what.
It doesn't even matter if they're commented out or not. They just need to be there.
What did I do wrong? Did I made a syntax error somewhere?