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);
Related
Hey guys I am trying to use a value that i got from a previous query in a new one, the value is a string stored in an array, they are the $Name and $Email variables, it looks like this when i var_dump them... string 'nathgold' (length=8) .... I want to use that nathgold as a value in the insert of a new query. I get the error Notice: Array to string conversion in C:\wamp\www\login\post.php on line 30
<?php
include_once('connect-db.php');
session_start();
if(!isset($_SESSION['isLogged']))
{
header("Location: home.php");
die();
}
if (!isset($_REQUEST['MBID'])) exit;
if (!isset($_REQUEST['Parent'])) {
$Parent = 0;
} else {
$Parent = $_REQUEST['Parent'];
}
if (isset($_POST['Title'])) {
$user_info=mysqli_query($connection, "SELECT * FROM usertest WHERE id=".$_SESSION['user']);
$userRow=mysqli_fetch_array($user_info);
$Name = $userRow=['username'];
$Email = $userRow=['email'];
$Title = mysqli_real_escape_string($connection, $_POST['Title']);
$Message = mysqli_real_escape_string($connection, $_POST['Message']);
$CurrentTime = time();
// other filtering here...
$result = mysqli_query($connection, "INSERT INTO mbmsgs (MBID, Parent, Poster, Email, Title, Message, DateSubmitted) VALUES ({$_REQUEST['MBID']}, $Parent, ".$Name.", ".$Email.", '$Title', '$Message', $CurrentTime);");
if ($result) {
echo "Your message has been posted - thanks!<br /><br />";
echo "Back to messageboard";
exit;
} else {
echo "There was a problem with your post - please try again.<br /><br />";
}
}
?>
<form method="post" action="post.php">
Message title: <input type"text" name="Title" /><br /><br />
Message:<BR />
<textarea name="Message" rows="10" cols="40"></textarea><br /><br />
<input type="hidden" name="MBID" value="<?php echo $_REQUEST['MBID']; ?>" />
<input type="hidden" name="Parent" value="<?php echo $Parent; ?>" />
<input type="submit" value="Post" />
</form>
You to convert $name on a string :
use implode("|",$name);
I'm going to keep it short and simple. I'm writing a really basic code in php which adds content to mysql db and I've run into an issue with editing. This is my form:
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
And this is my editIt.php
//session start and stuff
if(filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_STRING) == "POST")
{
echo "<script type='text/javascript'>alert('EDITIT!');</script>";
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("WebSiteDB") or die ("Cannot connect to database");
$id = $_POST['id'];
$details = mysql_real_escape_string($_POST['details']);
$time = strftime("%X");
$date = strftime("%B %d, %Y");
$isPublic = 'no';
foreach($_POST['public'] as $eachCheck)
{
if($eachCheck != NULL)
$isPublic = "yes";
}
mysql_query("UPDATE list SET details='$details', dateEdited='$date', timeEdited= '$time', public='$isPublic' WHERE id='$id'");
header("location: home.php");
}
I can't really find an issue with this code (which is not really strange, I'm a newbie at web stuff) and yet it just goes to home.php and does not change data in DB. Please, help me jump this ledge, so I can go on with my life.
I think, the problem is in this line $id = $_POST['id'];. On form submit, the input field value will only be submitted, not the DIV value.
So, please change from :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
To :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<input type="hidden" name="id" value="' . $id . '">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
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.
I am redirecting from here
Update
and code which shows error is
<?php include('../includes/connections.php'); ?>
<?php
try{
if(isset($_POST['submit'])){
$title = $_POST['title'];
$post = $_POST['post'];
$dates = $_POST['date'];
$sql = 'UPDATE `blog`.`contents` SET `titles` = :title, `posts` = :post, `dates` = :date WHERE `contents`.`id` = :idendity';
$result = $pdo->prepare($sql);
$result->bindValue(':title',$title);
$result->bindValue(':post',$post);
$result->bindValue(':date',$dates);
$result->bindValue(':idendity',$_GET['updid']);
$result->execute();
$count = $result->rowCount();
if($count == 1){
header('location: index.php');
}else{
echo 'Problem Occoured';
}
}
}
catch(PDOException $e){
echo "Problem: " .$e->getMessage();
}
?>
error which is shown:-Notice: Undefined index: updid in C:\xampp\htdocs\myblog\admin\update_post.php on line 13
Problem Occoured
<form action="update_post.php" method="post">
Title:<br/>
<input style="height:40px;" size="110" type="text" name="title" /><br />
Post:<br />
<textarea rows="30" cols="85" name="post" ></textarea><br />
Date:<br />
<input type="text" name="date" /><br/ >
<input type="submit" name="submit" />
</form>
yes by form submission and that is the reason i am checking for if submit isset or not.
You should include $_SESSION['id'] in a hidden field in the form:
<input type="hidden" name="updid" value="<?php echo $_SESSION['id']; ?>" />
... and change:
$result->bindValue(':idendity',$_GET['updid']);
... into:
$result->bindValue(':idendity',$_POST['updid']);
Edit
First of all, your question above has error. As mentioned in the comment, it's not possible that isset($_POST['submit']) will return true if you click on a link.
$_POST will have values when you access the page by submitting a form that has post in the method part.
As for $_GET, its values are taken from the query string of a URL:
http://yourpage.php?foo=bar&bar=foo
bar is the value of $_GET['foo']
foo is the value of $_GET['bar']
I've searched for basic $_POST/$_GET explanation but unable to find one :-D
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 />";
}