PHP code looks fine but not updating - php

I am currently creating a cms, all is fine apart from the add.php page.
My code for this page is this:
<?php
session_start();
include_once('../include/connection.php');
if (isset($_SESSION['logged_in'])){
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = nl2br($_POST['content']);
$image = $_POST['Image URL'];
$link = $_POST['Link'];
$price = $_POST['Price'];
if (empty($title) or empty($content)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6])');
$query->execute(array(
':title' => $title,
':content' => $content,
':image' => $image,
':link' => $link,
':price' => $price
));
$query->execute();
}if($result){
echo("<br>Input data is successful");
} else{
echo("<br>Input data failed");
}
}
?>
<html>
<head>
<title>testing</title>
<link rel="stylesheet" href="../style.css" />
</head>
<body>
<div class="container">
CMS
<br />
<h4>Add Article</h4>
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form name = "myform" action="add.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input type="text" name="Image URL" placeholder="Image URL" /><br /><br />
<input type="text" name="Link" placeholder="Link" /><br /><br />
<input type="text" name="Price" placeholder="Price" /><br /><br />
<input type="submit" name="submit" value="Add Article" />
</form>
</div>
</body>
</html>
<?php
}else{
header('location: index.php');
}
error_reporting(E_ALL);
?>
My problem is. My code is not showing any errors in my error log and people tellme that it is fine. But it is not adding to the database. is there a way that I can break down each bit of code and find out what is going on?
or is there a way to display what the error may be? my error reporting is turned on with E_ALL | E_STRICT and still nothing.
please help
thank you.

You need to change your PDO query from
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6])');
to be something like this
$query = $pdo->prepare('INSERT INTO `apps`(`app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES (:title,:content,:img,:link,:price)');
You should review how PDO::prepare method work with placeholders. Besides, if your app_id is an auto increment field. You need not include it in your insert query.

I'm not sure how this could work as the placeholders aren't using the correct notation and aren't named correctly.
Your query should look like:
$query = $pdo->prepare('INSERT INTO `apps`(`app_id`, `app_title`, `app_content`, `app_img`, `app_link`, `app_price`) VALUES (:app_id, :app_title, :app_content, :app_img, :app_link, :app_price)');
$query->execute(array(
':app_id' => ???,
':app_title' => $title,
':app_content' => $content,
':app_img' => $image,
':app_link' => $link,
':app_price' => $price
));
Also you appear to be missing the :app_id parameter.

Related

Edit functionality not works Php MySql

This is the code for edit.php where when I click edit this page opens and edits that specific line.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error){
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body><?php // if there are any errors, display them
if ($error != ''){echo '
<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label><br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" /><br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b><br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" /><br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" /><br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" /><br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" /><br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" /><br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" /><br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back();return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php } // connect to the database
include('connect.php');// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit'])){// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id'])){// get form data, making sure it is valid
$id = $_POST['id'];
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$telephone_number = mysql_real_escape_string(htmlspecialchars($_POST['telephone_number']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$job_title = mysql_real_escape_string(htmlspecialchars($_POST['job_title']));
$workplace = mysql_real_escape_string(htmlspecialchars($_POST['workplace']));
$country = mysql_real_escape_string(htmlspecialchars($_POST['country']));
$nationality = mysql_real_escape_string(htmlspecialchars($_POST['nationality']));// check that firstname/lastname fields are both filled in
if ($name == ''){// generate error message
$error = 'ERROR: Please fill in all required fields!';//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else{// save the data to the database
$link->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");// once saved, redirect back to the view page
header("Location: view.php");
}
}
else{// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else{ // if the form hasn't been submitted, get the data from the db and display the form
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0){// query db
$id = $_GET['id'];
$result = $link->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);// check that the 'id' matches up with a row in the databse
if($row){// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];// show form //renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else{// if no match, display result
echo "No results!";
}
}
else{// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
echo 'Error!';
}
}
?>
It gives first warning that mysql is deprecated so I used below syntax but still it gives error:
mysqli_real_escape_string(htmlspecialchars($link,$_POST['name']));
Second major error its giving is that it takes me to this error message and makes all form fields empty. The line its showing always is:
ERROR: Please fill in all required fields!
Please Guide!
$servername = "localhost:3306";
$username = "root";
$password = "<Password here>";
$dbname = "TUTORIALS";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tutorials_inf(name)VALUES ('".$_POST["name"]."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
$conn->close();
}
I Solved My-Self...
Code Below...
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Entries</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<div class="maindiv">
<?php include("includes/head.php");?>
<?php include("menu.php");?>
<!--HTML form -->
<div class="form_div">
<div class="title"><h2>Updating Report for ID: <?php echo $id;?></p></h2> </div>
<form action="" method="post">
<link rel="stylesheet" href="css\insert.css" type="text/css" />
<link rel="stylesheet" href="css\navcss.css" type="text/css" />
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<label>Name:</label><b><label style="margin-left:24em">الاسم</b></label>
<br />
<input class="input" type="text" name="name" value="<?php echo $name; ?>" />
<br />
<label>Telephone Number:</label><b><label style="margin-left:15em">رقم الهاتف</b>
<br />
<input class="input" type="text" name="telephone_number" value="<?php echo $telephone_number; ?>" />
<br />
<label>Email:</label></label><b><label style="margin-left:20em">البريد الإلكتروني</b></label>
<input class="input" type="text" name="email" value="<?php echo $email; ?>" />
<br />
<label>Job Title:</label></label><b><label style="margin-left:19em">المسمى الوظيفي</b></label>
<input class="input" type="text" name="job_title" value="<?php echo $job_title; ?>" />
<br />
<label>Work Place:</label></label><b><label style="margin-left:19em">جهه العمل</b></label>
<input class="input" type="text" name="workplace" value="<?php echo $workplace; ?>" />
<br />
<label>Country:</label></label><b><label style="margin-left:23em">الدولة</b></label>
<input class="input" type="text" name="country" value="<?php echo $country; ?>" />
<br />
<label>Nationality:</label></label><b><label style="margin-left:21em">الجنسية</b></label>
<input class="input" type="text" name="nationality" value="<?php echo $nationality; ?>" />
<br />
<p>* Required</p>
<input class="submit" type="submit" name="submit" value="Update Record" />
<button class="btnSubmit" type="submit" value="Submit" onclick="history.back(); return false;">Return to previous page</button>
</form>
</div>
</div>
</body>
</html>
<?php
}
// connect to the database
$mysqli = new mysqli("sql213.byethost7.com", "b7_21234466", "mazhar2012", "b7_21234466_conference");
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$name = $mysqli->real_escape_string($_POST['name']);
//$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
//$last_name = mysql_real_escape_string(htmlspecialchars($_POST['last_name']));
$telephone_number = $mysqli->real_escape_string($_POST['telephone_number']);
$email = $mysqli->real_escape_string($_POST['email']);
$job_title = $mysqli->real_escape_string($_POST['job_title']);
$workplace = $mysqli->real_escape_string($_POST['workplace']);
$country = $mysqli->real_escape_string($_POST['country']);
$nationality = $mysqli->real_escape_string($_POST['nationality']);
// check that firstname/lastname fields are both filled in
if ($name == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $telephone_number, $email, $job_title, $workplace, $country, $nationality, $error);
}
else
{
// save the data to the database
$mysqli->query("UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = $mysqli->query("SELECT * FROM conf WHERE id=$id");
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$name=$row['name'];
$telephone_number = $row['telephone_number'];
$email = $row['email'];
$job_title = $row['job_title'];
$workplace = $row['workplace'];
$country = $row['country'];
$nationality = $row['nationality'];
// show form
//renderForm($id, $first_name,$emp_number,$department,$email, '');
renderForm($id, $name, $telephone_number, $email,$job_title,$workplace,$country,$nationality, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
$link->query($conn,"UPDATE conf SET name='$name', telephone_number='$telephone_number',email='$email',job_title='$job_title',workplace='$workplace',country='$country',nationality='$nationality' WHERE id=$id");

Updating post with PHP & MySQL

I'm building a sort of blog system, but I'm having trouble with editing an existing 'post' in the system. It is collecting the data from the database, and it displays it. But when I click the update button, I get this error. I've looked for it, checked my code couple of times, but I just couldn't find anything. This is the error.
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
And this is my code.
<?php //include config
require_once('../../includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bewerk</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link rel="stylesheet" href="../style/normalize.css">
<link rel="stylesheet" href="../style/main.css">
<link rel="stylesheet" href="../style/login.css">
</head>
<body>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo $error.'<br />';
}
}
try {
$stmt = $db->prepare('SELECT patient_id, voornaam, achternaam, leeftijd, lengte, gewicht, foto_url FROM patienten WHERE patient_id = :patient_id') ;
$stmt->execute(array(':patient_id' => $_GET['id']));
$row = $stmt->fetch();
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){
$_POST = array_map( 'stripslashes', $_POST );
//collect form data
extract($_POST);
if(!isset($error)){
try {
//insert into database
$stmt = $db->prepare('UPDATE patiënten SET patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
':patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
//redirect to index page
header('Location: index.php?action=updated');
exit;
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
?>
<div class="row">
<div class="col-md-2 col-md-offset-5">
<img src="../style/images/logo.png">
</div>
</div>
<div class="keuze_link row">
<p><b><?php echo $row['voornaam'];?> <?php echo $row['achternaam'];?></b> bewerken</p>
</div>
<div class="container">
<form class="toevoegen" action="" method="post">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];? >">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>
</div>
</body>
</html>
If you guys wanna know more, or see more code, I'd like to hear it. Thanks in advance.
EDIT. for update.
//insert into database
$stmt = $db->prepare('UPDATE patienten SET patient_id = :patient_id, voornaam = :voornaam, achternaam = :achternaam, leeftijd = :leeftijd, lengte = :lengte, gewicht = :gewicht, foto_url = :foto_url WHERE patient_id = :patient_id') ;
$stmt->execute(array(
'patient_id' => $patient_id,
':voornaam' => $voornaam,
':achternaam' => $achternaam,
':leeftijd' => $leeftijd,
':lengte' => $lengte,
':gewicht' => $gewicht,
':foto_url' => $foto_url
));
Latest form for update
<form class="toevoegen" action="" method="post">
<input type="hidden" name="voornaam" value="<?php echo $row['patient_id'];?>">
<input type="text" name="voornaam" value="<?php echo $row['voornaam'];?>">
<br>
<input type="text" name="achternaam" value="<?php echo $row['achternaam'];?>">
<br>
<input type="text" name="leeftijd" value="<?php echo $row['leeftijd'];?>">
<br>
<input type="text" name="lengte" value="<?php echo $row['lengte'];?>">
<br>
<input type="text" name="gewicht" value="<?php echo $row['gewicht'];?>">
<br>
<input type="text" name="foto_url" value="<?php echo $row['foto_url'];?>">
<br>
<input class="button" type="submit" name="submit" value="Updaten!">
</form>
:patient_id is missing from the $stmt->execute() function. Please add it and try again.
In your update query you forgot about :patient_id to bind
And yes, remove $ before column names.

Not inserting data into database

I'm trying to get my PHP/HTML back up to scratch, and I've started by designing my own little news/whatever system. What I'm trying to do for efficiency is to run the Add/Edit/Delete all from the one process.php file via a switch($x), but for some reason it won't insert any data, and it won't give me any errors. I'm completely lost on what to do here. If anyone could help me out the code for both files is as below.
process.php
<?php
include("config.php");
if (!isset($_GET['x'])) {
$x = $_GET[x];
switch($x) {
case "add":
$title = $_POST['title'];
$text = $_POST['text'];
$date = $_POST['date'];
$author = $_POST['author'];
mysql_query("INSERT INTO posts(id, title, text, date, author) VALUES(null, '$title', '$text', '$date', '$author')") or die(mysql_error());
echo("Article inserted. Click <a href=\"index.php\" />here</a> to return.");
break;
case "gohome":
echo("Looks like you've taken a wrong turn. Click here to return.");
default:
echo("Go home.");
break;
}
} else {
$x = 'gohome';
}
?>
index.php (adding data)
<html>
<head>
<link rel="stylesheet" type="text/css" href="includes/style.css" />
</head>
<body>
<div align="center" /><font size="20px;" />test</font></div>
<?php include("includes/navigation.php"); ?>
<div align="center" />
<fieldset><legend>Submit an article</legend>
<form action="includes/process.php?x=add" method="post" />
<input name="title" type="text" value="Title" onfocus="if(this.value=='Title') this.value='';" onblur="if(this.value=='') this.value='Title';"/><br />
<input name="date" type="text" value="Date" onfocus="if(this.value=='Date') this.value='';" onblur="if(this.value=='') this.value='Date';"/><br />
<textarea rows="4" cols="50" name="text" /></textarea><br />
<input name="author" type="text" value="Author" onfocus="if(this.value=='Author') this.value='';" onblur="if(this.value=='') this.value='Author';"/><br />
<input type="submit" />
</form>
</fieldset>
</body>
</html>
This code:
if (!isset($_GET['x'])) {
$x = $_GET[x];
should be:
if (isset($_GET['x'])) {
$x = $_GET['x'];
You had the test backwards, so when the parameter was set you weren't going into the switch.

Add function won't work on database

Hello everyone I'm studying php + html this semester and I got stuck on this code.
Everything works (list + delete from db) but adding for some reason won't add to the db even though it does validate the inputs and give the code number at the end of URL using the header function. Yes I did include the page that addProduct function at :)
here is the code if anyone can give me an advice or hint
PHP Code:
if ( $action == 'add_product' ) {
$code = $_POST['code'];
$name = $_POST['name'];
$version = $_POST['version'];
$releaseDate = $_POST['releaseDate'];
if (empty($code) || empty($name) || empty($version) || empty($releaseDate)) {
$error = "Please enter a valid and correct values.";
include('../errors/error.php');
exit();
} else {
addProduct($code, $name, $version, $releaseDate);
header("Location: .?code=$code");
}
}
here is the addProduct function
function addProduct($code, $name, $version, $releaseDate){
global $db;
$query = "INSERT INTO products
(productCode, name, version, releaseDate)
VALUES
('$code', '$name', '$version' '$releaseDate')";
$db->exec($query);
}
and this is the HTML Code
<form action="index.php" method="post">
<input type="hidden" name="action" value="add_product"/>
<label>Code:</label> <input type="input" name="code"/>
<br />
<label>Name:</label><input type="input" name="name"/>
<br />
<label>Version:</label><input type="input" name="version"/>
<br />
<label>Release Date:</label><input type="input" name="releaseDate"/> <label>Use 'yyyy-mm-dd' format</label>
<br />
<label> </label>
<input type="submit" name="submit" value="Add Product" />
<br /> <br />
</form>
Thanks :)
Is it just me or you are missing a comma here in your function?
VALUES ('$code', '$name', '$version' '$releaseDate')";
You may use mysql_query($query); instead of $db->exec($query);

Codeigniter Noob problems

I am noob in CI and I can't insert a data in database, here is all I have done, it doesn't show me an error but i don't get a result,
admin.php (controller)
public function postnews(){
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip == "my ip address"){
session_start();
if (!isset($_SESSION['admin'])){
$this->load->view('admin-login');
die(0);
}
if ($_SESSION['admin'] != 'loged'){
$this->load->view('admin-login');
die(0);
}
if ($_SESSION['admin'] == 'loged'){
if (isset($_POST['title'])and isset($_POST['main-poster']) and isset($_POST['type']) and isset($_POST['year']) and isset($_POST['language'])and isset($_POST['platform'])and isset($_POST['publisher'])and isset($_POST['size'])and isset($_POST['graphics'])and isset($_POST['little-info'])and isset($_POST['full-info'])and isset($_POST['posters'])and isset($_POST['screenshots'])and isset($_POST['trailers'])and isset($_POST['gameplays'])and isset($_POST['author'])){
$title = $_POST['title'];
$main_poster = $_POST['main-poster'];
$type = $_POST['type'];
$year = $_POST['year'];
$language = $_POST['language'];
$platform = $_POST['platform'];
$publisher = $_POST['publisher'];
$size = $_POST['size'];
$graphics = $_POST['graphics'];
$little_info = $_POST['little-info'];
$full_info = $_POST['full-info'];
$posters = $_POST['posters'];
$screenshots = $_POST['screenshots'];
$trailers = $_POST['trailers'];
$gameplays = $_POST['gameplays'];
$autor = $_POST['author'];
$date = date("d.m.Y");
$this->load->model('Gamesmodel');
echo $this->Gamesmodel->PostArticle($title, $main_poster, $type, $year, $language, $platform, $publisher, $size, $graphics, $little_info, $full_info, $posters, $screenshots, $trailers, $gameplays, $autor, $date);
}else{
$this->load->view('postnews');
}
}
} else {
$this->load->view('404.htm');
die(0);
}
}
gamemodel.php model
<?php
class Gamesmodel extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function PostArticle($title, $main_poster, $type, $year, $language, $platform, $publisher, $size, $graphics, $little_info, $full_info, $posters, $screenshots, $trailers, $gameplays, $autor, $date)
{
$sql = "INSERT INTO game-articles (id, title, type, year, language, platform, publisher, size, graphics, little-info, full-info, posters, screenshots, trailers, gameplays, date, author) VALUES ('' ,".$this->db->escape($title).",".$this->db->escape($main_poster).",".$this->db->escape($type).",".$this->db->escape($year).",".$this->db->escape($language).",".$this->db->escape($platform).",".$this->db->escape($publisher).",".$this->db->escape($size).",".$this->db->escape($graphics).",".$this->db->escape($little_info).",".$this->db->escape($full_info).",".$this->db->escape($posters).",".$this->db->escape($screenshots).",".$this->db->escape($trailers).",".$this->db->escape($gameplays).",".$this->db->escape($date).",".$this->db->escape($author).")";
$this->db->query($sql);
return $this->db->affected_rows();
}
}
postnews.php view
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Post News</title>
</head>
<body style="background-color:black;">
<div style="margin:auto auto auto auto; width:800px; background-color:white; padding-top:20px; padding-bottom:20px; text-align:center;">
<form action="http://www.gameslib.net/admin/postnews" method="post"><br />
<input type="text" placeholder="title" name="title" style="width:300px;" /><br />
<input type="text" placeholder="main poster" name="main-poster" style="width:300px;" /><br />
<input type="text" placeholder="type" name="type" style="width:300px;" /><br />
<input type="text" placeholder="year" name="year"/><br />
<input type="text" placeholder="language" name="language" style="width:300px;" /><br />
<input type="text" placeholder="platform" name="platform" style="width:300px;" /><br />
<input type="text" placeholder="publisher" name="publisher" style="width:300px;" /><br />
<input type="text" placeholder="size" name="size"/><br />
<input type="text" placeholder="graphics" name="graphics" style="width:300px;" /><br />
<textarea name="little-info" placeholder="little-info" style="width:600px; height:100px;" ></textarea><br />
<textarea name="full-info" placeholder="full-info" style="width:600px; height:200px;" ></textarea><br />
<textarea name="posters" placeholder="posters" style="width:600px; height:50px;" ></textarea><br />
<textarea name="screenshots" placeholder="screenshots" style="width:600px; height:50px;" ></textarea><br />
<textarea name="trailes" placeholder="trailes" style="width:600px; height:50px;" ></textarea><br />
<textarea name="gameplays" placeholder="gameplays" style="width:600px; height:50px;" ></textarea><br />
<input type="text" placeholder="author" name="author" /><br />
<input type="submit" value="P O S T"/><br />
<input type="reset" value="reset"/><br />
</form>
</div>
</body>
</html>
please help me, I copied allmost everything to be shure I am not ignoring something,
Ok, lets start by clearing up your code. Instead of having to create each independent variable in your if ($_SESSION['admin'] == 'loged') method, you can use the function extract();. The extract() method creates a variable for each key in the provided array. Say you have the key name in the array $_POST, the extract method will create a variable named name for you. To retrieve the value, all you need to do is access the variable $name.
if ($_SESSION['admin'] == 'loged'){
extract($_POST);
}
Secondly, you don't use the word and if you want to check more than one thing in an if statement, you use the following operand '&&'.
if (isset($_POST['title']) && isset($_POST['main-poster']) && isset($_POST['type']) && isset($_POST['year']) && isset($_POST['language']) && isset($_POST['platform']) && isset($_POST['publisher']) && isset($_POST['size']) && isset($_POST['graphics']) && isset($_POST['little-info']) && isset($_POST['full-info']) && isset($_POST['posters']) && isset($_POST['screenshots']) && isset($_POST['trailers']) && isset($_POST['gameplays']) && isset($_POST['author']))
Instead of manually checking to see if each object has been set in the $_POST array, you can just iterate through $_POST.
Create an array of the variables that you need to be set:
$req_fields = array(
'title',
'main-poster',
'type',
'year',
'language',
'platform',
'publisher',
'size',
'graphics',
'little-info',
'full-info',
'posters',
'screenshots',
'trailers',
'gameplays',
'author'
);
Then create an array for the elements that haven't been set:
$notset = array();
Finally, iterate through $_POST checking to see if each value is set. If not, add it to the array.
foreach ($req_fields as $key) {
if (!isset($_POST[$key]) {
$notset[] = $key;
}
}
Then check to see if any values have not been set and redirect the user, else, load the model and echo the post:
if (count($notset) > 0) {
$this->load->view('postnews');
}
else {
$this->load->model('Gamesmodel');
echo $this->Gamesmodel->PostArticle($title, $main_poster, $type, $year, $language, $platform, $publisher, $size, $graphics, $little_info, $full_info, $posters, $screenshots, $trailers, $gameplays, $autor, $date);
}
Presumably the actual reason behind the insert not working is because it isn't actually called. The reason behind this would be that some of the keys were not actually set.
Iterate through the $notset array to see if this is the case:
foreach ($notset as $unsetField) {
echo "Field {$unsetField} is not set. <br />";
}

Categories