/    Sign up×
Community /Pin to ProfileBookmark

another problem with pdo insert

Hi guys. working my way through a tutorial. i have a form with a text input, a select input, a file input and a textarea input. i think the problem is with the file input as when i select a file on the form page and hover over it after it doesnt show the file name like it does in the tutorial. whatever is happenning the data isnt going to the atabase table. would the dodgy file input prevent that? all the code is in the one page but ill break up the php from the html

[CODE]
<?php require_once(“includes/db.php”);?>
<?php require_once(“includes/functions.php”);?>
<?php require_once(“includes/sessions.php”);?>
<?php
ini_set(‘display_errors’, true); // set to false in production
error_reporting(E_ALL);
?>

<?php

if(isset($_POST[“submit”])){
$postTitle = $_POST[“postTitle”];
$category = $_POST[“category”];
$image = $_FILES[“image”][“name”];
$target = “uploads/”.basename($_FILES[“image”][“name”]);
$postDescription = $_POST[“postDescription”];
$admin = “cole”;
date_default_timezone_set(“Europe/Dublin”);
$currenttime = time();
$datetime= strftime(“%B-%d-%Y %H:%M:%S”, $currenttime);

if(empty($postTitle)){
$_SESSION[“error”] = “please add a post title”;
redirect(“addnewpost.php”);
}elseif(strlen($postTitle)<5){
$_SESSION[“error”] = “post title must be longer than 5 charachters”;
redirect(“addnewpost.php”);
}elseif(strlen($postDescription)>999){
$_SESSION[“error”] = “post must be less than 1000 charachters”;
redirect(“addnewpost.php”);
}else {
$sql = “INSERT INTO posts(datetime,title,category,author,image,post) VALUES(:entrytime,:postTitle,:postCategory,:adminName,:pic,:postText)”;
$stmt = $connect->prepare($sql);
$stmt->bindValue(‘:entrytime’,$datetime);
$stmt->bindValue(‘:postTitle’,$postTitle);
$stmt->bindValue(‘:postCategory’,$category);
$stmt->bindValue(‘:admiNname’,$admin);
$stmt->bindValue(‘:pic’,$image);
$stmt->bindValue(‘:postText’,$postDescription);
$Execute = $stmt->execute();

if($Execute){
$_SESSION[“success”] = “data added successfully”;
redirect(“addnewpost.php”);
}else {
$_SESSION[“error”] = “something went wrong. data not added to table”;
redirect(“addnewpost.php”);
}
}
}

?>
[/CODE]

HTML

[CODE]
<!doctype html>
<html>

<head>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<meta http-equiv=”X-UA-compatible” content=”ie=edge”>
<title>Add new post</title>
<link rel=”stylesheet” href=”https://use.fontawesome.com/releases/v5.7.2/css/all.css” integrity=”sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr” crossorigin=”anonymous”>
<link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css” integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T” crossorigin=”anonymous”>
<link rel=”stylesheet” href=”css/styles.css”>
</head>

<body>

<!– NAVBAR START –>
<div style=”height:10px; background-color:rgb(100,100,100);”></div>
<nav class=”navbar navbar-expand-lg bg-dark navbar-dark”>
<div class=”container”>
<a href=”#” class=”navbar-brand”>jazebakram.com</a>
<button class=”navbar-toggler” data-toggle=”collapse” data-target=”#navbarcollapsecms”><span class=”navbar-toggler-icon”></span></button>
<div class=”collapse navbar-collapse” id=”navbarcollapsecms”>
<ul class=”navbar-nav mr-auto”>
<li class=”nav-item”><a href=”myprofile.php” class=”nav-link”> <i class=”fas fa-user”></i> Profile</a></li>
<li class=”nav-item”><a href=”dashboard.php” class=”nav-link”>Dashboard</a></li>
<li class=”nav-item”><a href=”posts.hp” class=”nav-link”>Posts</a></li>
<li class=”nav-item”><a href=”catagories.php” class=”nav-link”>Catagories</a></li>
<li class=”nav-item”><a href=”admins.php” class=”nav-link”>Manage admins</a></li>
<li class=”nav-item”><a href=”comments.php” class=”nav-link”>Comments</a></li>
<li class=”nav-item”><a href=”blog.php?page=1″ class=”nav-link”>Live blog</a></li>
</ul>
<ul class=”navbar-nav ml-auto”>
<li class=”nav-item”><a href=”logout.php” class=”nav-link”><i class=”fas fa-user-times”></i> Log out</a></li>
</ul>
</div>
</div>
</nav>
<div style=”height:10px; background-color:rgb(100,100,100);”></div>
<!– NAVBAR END –>

<!– HEADER START –>
<header class=”bg-dark text-white”>
<div class=”container”>
<div class=”row”>
<h1> <i class=”fas fa-edit style=”color: #27aae1;”></i> Manage posts</h1>
</div>
</div>
</header>
<!– HEADER END –>

<!– MAIN AREA –>
<section class=”container py-2 mb-4″>
<div class=”row”>
<div class=”offset-lg-1 col-lg-10″ style=”min-height: 600px;”>
<?php
echo errormessage();
echo successmessage();
?>
<form action=”addnewpost.php” method=”post” enctype=”multipart/form-data”>
<div class=”card bg-secondary text-light “>

</div>
<div class=”card-body bg-dark” >
<div class=”form-group”>
<label for=”postTitle”><span class=”fieldinfo”>post title:</span></label>
<input class=”form-control” type=”text” name=”postTitle” id=”postTitle”>
</div>
<div class=”form-group”>
<label for=”category title”><span class=”fieldinfo”>choose Category:</span></label>
<select class=”form-control” id=”categoryTitle” name=”category”>
<?php

global $connect;

$sql = “SELECT * FROM category”;
$stmt = $connect->query($sql);
while ($daterows = $stmt->fetch()){
$categoryname = $daterows[“title”];
echo “<option> $categoryname </option>”;
}
?>

?>
</select>
</div>
<div class=”form-group”>
<div class=”custom-file”>
<input type=”file” name=”image” id=”imageselect” value=””>
<label for=”imageselect”class=”custom-file-label”>Select image</label>
</div>
</div>
<div class=”form-group”>
<label for=”post”><span class=”fieldinfo”>Post:</span></label>
<textarea class=”form-control” id=”post” name=”postDescription” rows=”8″ cols=”80″></textarea>
</div>
<div class=”row”>
<div class=”col-lg-6 mb-2″>
<a href=”dashboard.php” class=”btn btn-warning btn-lg btn-block”><i class=”fas fa-arrow-left”>Back to dashboard</i></a>
</div>
<div class=”col-lg-6 mb-2″>
<button type=”submit” name=”submit” class=”btn btn-success btn-lg btn-block”><i class=”fas fa-check”>Publish</i></button>
</div>
</div>
</div>
</form>
</div>
</div>
</section>

<!– FOOTER START –>
<footer class=”bg-dark text-white”>
<div class-“container”>
<div class=”row”>
<div class=”col”>
<p class=”lead text-center”>Theme by Cole Pratt</p>
</div>
</div>
</div>
</footer>

<script src=”https://code.jquery.com/jquery-3.3.1.slim.min.js” integrity=”sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo” crossorigin=”anonymous”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js” integrity=”sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1″ crossorigin=”anonymous”></script>
<script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js” integrity=”sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM” crossorigin=”anonymous”></script>
</body>

</html>

[/CODE]

to post a comment
PHP

13 Comments(s)

Copy linkTweet thisAlerts:
@coleioauthorMar 22.2019 — i have errors turned on and its not showing anything either
Copy linkTweet thisAlerts:
@NogDogMar 22.2019 — Start by adding something right after the test to see if you actually get into the form-processing code, like...
<i>
</i>if(isset($_POST["submit"])){
die("Got here!");

If you get there when you submit the form, then move that down into other conditional or loop blocks, or to inspect the $_POST and $_FILES arrays, and so forth, until you find where something is not as expected.
<i>
</i>if(isset($_POST["submit"])){
die("&lt;pre&gt;POST:n".print_r($_POST, 1)."nnFILES:n".print_r($_FILES, 1)."&lt;/pre&gt;");

...and so forth, until you find something that does not match expectations, and then debug it to find out why.
Copy linkTweet thisAlerts:
@coleioauthorMar 22.2019 — thanks Nogdog. i definately have alot to learn. ok so it does show the contents of the post and files arrays. thats all working. also the validation i did before the sql part and after the post variable assignment is working also so that only leaves the sql part. can anyone spot anything wrong with that?

here it is

db connect file
[CODE]
<?php

$DSN = "mysql:host = localHost; dbname=cms";
$connect = new PDO($DSN, 'root', '');
?>

[/CODE]


the insert query
[CODE]
else {
$sql = "INSERT INTO posts(datetime,title,category,author,image,post) VALUES(:entrytime,:postTitle,:postCategory,:adminName,:pic,:postText)";
$stmt = $connect->prepare($sql);
$stmt->bindValue(':entrytime',$datetime);
$stmt->bindValue(':postTitle',$postTitle);
$stmt->bindValue(':postCategory',$category);
$stmt->bindValue(':admiNname',$admin);
$stmt->bindValue(':pic',$image);
$stmt->bindValue(':postText',$postDescription);
$Execute = $stmt->execute();



if($Execute){
$_SESSION["success"] = "data added successfully";
redirect("addnewpost.php");
}else {
$_SESSION["error"] = "something went wrong. data not added to table";
redirect("addnewpost.php");
}
}
[/CODE]
Copy linkTweet thisAlerts:
@coleioauthorMar 22.2019 — i do have the following code in the html to populate the select element i figured thatit might interfere with the insert code

[CODE]
<?php

global $connect;

$sql = "SELECT * FROM category";
$stmt = $connect->query($sql);
while ($daterows = $stmt->fetch()){
$categoryname = $daterows["title"];
echo "<option> $categoryname </option>";
}
?>
[/CODE]


i noticed stmt and sql variable being used there aswell so i changed the variables in the insert statement to $sql1 and $stmt1 but that didnt change anything.
Copy linkTweet thisAlerts:
@coleioauthorMar 22.2019 — would something like this

https://stackoverflow.com/questions/2518354/php-mysql-pdo-prepared-insert-does-not-work-and-no-error-messages

help me detirmine the problem?
Copy linkTweet thisAlerts:
@coleioauthorMar 22.2019 — i added this in the last else condition that sets the error message

[CODE]
echo "nPDO::errorInfo():n";
print_r($dbh->errorInfo());
[/CODE]


And it threw the following errors. can anyone help me decipher it?

[CODE]
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:xampphtdocscmsaddnewpost.php on line 41
PDO::errorInfo():
Notice: Undefined variable: dbh in C:xampphtdocscmsaddnewpost.php on line 50

Fatal error: Call to a member function errorInfo() on null in C:xampphtdocscmsaddnewpost.php on line 50
[/CODE]
Copy linkTweet thisAlerts:
@NogDogMar 22.2019 — Try enabling PDO exceptions when you create your PDO connection:
<i>
</i>$DSN = "mysql:host = localHost; dbname=cms";
$connect = new PDO($DSN, 'root', '');
$connect-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Then wrap your form-proccessing code in a try/catch block:
<i>
</i>try {
// your code...
}
catch(PDOException $e) {
die("&lt;pre&gt;PDO error:n".var_export($e, 1)."&lt;/pre&gt;");
}
catch(Exception $e) {
die("&lt;pre&gt;Other exception:n".var_export($e, 1)."&lt;/pre&gt;");
}

Note: You will not want to dump debug info like that on the live site, so you'd want to ultimately change those catch() blocks to do something like using error_log() to log the error info then display some generic user-friendly "Oops" message to the user. :)
Copy linkTweet thisAlerts:
@ginerjmMar 22.2019 — Using upper and lower case names will bite you in the A. Is there some serious reason behind your choosing to use them?

I don't know why you aren't getting an error here but I would think that since this argument isn't being used sql would have an issue with it
<i>
</i> $stmt-&gt;bindValue(':admiNname',$admin);

All lower case is the best way to go IMHO. How many times already have you had to go back thru code to see how you spelled something before you type it in the next time?
Copy linkTweet thisAlerts:
@ginerjmMar 22.2019 — As directed above do something like this with your code:
<i>
</i>&lt;?php
require_once("includes/db.php");
require_once("includes/functions.php");
require_once("includes/sessions.php");
ini_set('display_errors', true); // set to false in production
error_reporting(E_ALL);
//*************
if(isset($_POST["submit"]))
{
echo "Handling submit button at line ".__LINE__."&lt;br&gt;";
$postTitle = $_POST["postTitle"];
$category = $_POST["category"];
$image = $_FILES["image"]["name"];
$target = "uploads/".basename($_FILES["image"]["name"]);
$postDescription = $_POST["postDescription"];
$admin = "cole";
date_default_timezone_set("Europe/Dublin");
$currenttime = time();
$datetime= strftime("%B-%d-%Y %H:%M:%S", $currenttime);
if(empty($postTitle))
{
$_SESSION["error"] = "please add a post title";
redirect("addnewpost.php");
}
elseif(strlen($postTitle)&lt;5)
{
$_SESSION["error"] = "post title must be longer than 5 charachters";
redirect("addnewpost.php");
}
elseif(strlen($postDescription)&gt;999)
{
$_SESSION["error"] = "post must be less than 1000 charachters";
redirect("addnewpost.php");
}
else
{
echo "Building query 1 at line ".__LINE__."&lt;br&gt;";
$sql = "INSERT INTO posts(datetime,title,category,author,image,post) VALUES(:entrytime,:postTitle,:postCategory,:adminName,:pic,:postText)";
$stmt = $connect-&gt;prepare($sql);
$stmt-&gt;bindValue(':entrytime',$datetime);
$stmt-&gt;bindValue(':postTitle',$postTitle);
$stmt-&gt;bindValue(':postCategory',$category);
$stmt-&gt;bindValue(':admiNname',$admin);
$stmt-&gt;bindValue(':pic',$image);
$stmt-&gt;bindValue(':postText',$postDescription);
$Execute = $stmt-&gt;execute();
if($Execute)
{
echo "Query 1 executed";
exit();
$_SESSION["success"] = "data added successfully";
redirect("addnewpost.php");
}else
{
echo "Query 1 did not run";
exit();
$_SESSION["error"] = "something went wrong. data not added to table";
redirect("addnewpost.php");
}
}
}

Note the lack of php on and off tags. And the inclusion of echo statements to tell you how far your script gets and what line it is. I also used an exit after the query process just to shorten the debug trail.

Note the indentation used also. Your choice on where to place the {} but I like the way I do it. Makes it easy to read.
Copy linkTweet thisAlerts:
@NogDogMar 22.2019 — > @ginerjm#1602124 $stmt-&gt;bindValue(':admiNname',$admin);

Actually, a good catch in that it should be ':adminName' (not ':admiName'); which, to your point, probably _would_ be more obvious if it were a "snake-cased" ':admin_name'.

However, lots of people prefer camelCaseNames, and others prefer snake_case_names...but very few like Snakey_Camel_Case_Names. ;)
Copy linkTweet thisAlerts:
@ginerjmMar 22.2019 — IMHO it just seems like too much work to choose a specific odd name value and then have to remember it forever as you work on that script. Especially when one doesn't even use a consistent pattern for doing it (sorry OP). A couple hundred lines later and you're scrolling up and down to look for how you did it the first time when you need to use it a second time. All lower works for me - that way I always know how to spell it forever!
Copy linkTweet thisAlerts:
@coleioauthorMar 22.2019 — No need to be sorry ginerjm you're perfectly right I'm just following a tutorial and didn't expect to run into any problems. Funnily enough the bug was a capital letter in one of the bindvalue placeholders. Appreciate your input guys thanks
Copy linkTweet thisAlerts:
@ginerjmMar 23.2019 — And now you see why I recommend to NOT use caps at random in your php names. Even AT ALL is my preferred choice!


Did you know that there are very few computer languages that are case-sensitive? I spent 30 years in programming and never had to be concerned with it. Then I pick up PHP and JS and boom! Case suddenly mattered.
×

Success!

Help @coleio spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.27,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...