Codeigniter Noob problems - php

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 />";
}

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");

Notice: Undefined index variable. PHP script works on Linux but not Windows

I have a PHP script that works on Linux but not on Windows.
I can accept that my PHP coding isn't that great, I'm a newbie.
I have a form, and I post the data to it. Now that it is on a Windows server, I get:
Notice: Undefined index: nmr in C:\Apache24\htdocs\index.php on line 31
...
and so on.
I tried declaring all the variables as 0, and using isset, but it doesn't seem to work.
Perhaps I'm using isset wrong. Can someone help me?
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" href="http://www.hackmaine.org/favicon.ico">
<link rel="stylesheet" type="text/css" href="sty.css">
<title>NMR Scheduler</title>
</head>
<body>
<?PHP
$Unity = 'unchecked';
$Inova = 'unchecked';
$Experiment = $duration = $ToD = $startTime = $ddate = $nmr = $UName = 0;
if (isset($_POST['Submit1']))
{
$selected_radio = $_POST['nmr'];
switch ($selected_radio)
{
case Unity:
break;
case Inova:
break;
default:
echo "Select an NMR";
}
}
isset($Experiment, $duration, $ToD, $startTime, $ddate, $UName);
$reg_wvar=$_POST['nmr'];
$reg_UName=$_POST['UName'];
$reg_Date=$_POST['ddate'];
$reg_startTime=$_POST['startTime'];
$reg_ToD=$_POST['ToD'];
$reg_duration=$_POST['duration'];
$reg_Experiment=$_POST['Experiment'];
$stringy = "$reg_wvar, $reg_UName, $reg_Date, $reg_startTime $reg_ToD, $reg_duration, $reg_Experiment \n";
echo $stringy;
$filename = 'newEntry.txt';
// Let's make sure the file exists and is writeable first.
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $stringy) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
//echo "Success, wrote ($somecontent) to file ($filename)";
fclose($handle);
} else {
echo "Data not written, Make Sure you selected an NMR";
}
?>
<center>
<FORM ACTION="if.php" method="post">
<h2>NMR Usage Scheduler</h2>
<br /><br />
<INPUT TYPE = 'Radio' Name ='nmr' value= 'Unity'>Unity
<INPUT TYPE = 'Radio' Name ='nmr' value= 'Inova' >Inova<br /><br />
<B>Your Name :</B><input type="text" size="20" maxlength="10" name="UName" required><br /><br />
<B>Enter Date (mm/dd):</B> <input type="text" size="20" maxlength="5" name="ddate" required><br /><br />
<B>Start Time (hh:mm):</B> <input type="text" size="8" maxlength="5" name="startTime" required>
<INPUT TYPE = 'Radio' Name ='ToD' value= 'AM' >AM
<INPUT TYPE = 'Radio' Name ='ToD' value= 'PM' checked>PM
<br /><br />
<B>Duration: </B> <input type="text" size="20" maxlength="5" name="duration" required><br /><br />
<B>Experiment:</B> <input type="text" size="20" maxlength="5" name="Experiment" required><br /><br />
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Submit">
</FORM>
</center>
</body>
</html>
if(isset($_POST['nmr'], $_POST['UName'], ...) {
$reg_wvar=$_POST['nmr'];
$reg_UName=$_POST['UName'];
...
}

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.

PHP code looks fine but not updating

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.

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);

Categories