I am having trouble of finding why my code is not working . I tried to look up on the internet but I can't seem to find the error.
Here's my function
public function AddNews($newsDate,$title,$content){
try{
$stmt = $this->db->prepare("INSERT INTO news(newsDate,title,content) VALUES (:newsDate,:$title,:$content)");
$stmt->bindParam(":newsDate", $newsDate);
$stmt->bindParam(":title", $title);
$stmt->bindParam(":content", $content);
$stmt->execute();
return $stmt;
}catch(PDOException $ex){
echo $ex->getMessage();
}
}
and the form action
/*---------DEVELOPMENT-----------*/
require_once '/database/database.php';
/*---------ENVIRONMENT-----------*/
// require_once 'database/database.php';
if(isset($_POST['btn-news-submit'])){
$newsDate = trim($_POST['newsDate']);
$title = trim($_POST['bodyContent']);
$content = trim($_POST['newsContent']);
if($user->AddNews($newsDate,$title,$content)){
header("Location: admin-index.php?successfully-uploaded");
}
}
and lastly my html form
<div class="news">
<form action = "upload-news" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="hidden" name="newsDate" id="newsDate" value="<?php echo date('Y-m-d H:i:s'); ?>" readonly="readonly">
<label for="bodyContent"><b>Title</b></label>
<textarea class="form-control" rows="1" id="bodyContent" name="bodyContent"></textarea>
<br>
<label for="exampleFormControlFile1">Content of News</label>
<textarea class="form-control" rows="5" id="newsContent" name="newsContent"></textarea>
<br />
<br>
<div class="btn-news">
<button type="submit" name="btn-news-submit" class="btn btn-primary">Post</button>
</div>
</div>
</form>
</div>
Could someone please point out where is the error here . It says
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
But I checked several times and all my bindParam are matched
Don't use dollar signs in your bind handles here:
"INSERT INTO news(newsDate,title,content) VALUES (:newsDate,:$title,:$content)"
^ ^
Just use plain strings like this:
"INSERT INTO news(newsDate,title,content) VALUES (:newsDate,:title,:content)"
Related
I have form consist item_id , item_name , item_price and item_bio at the end have input tybe submit like this
<form method="POST" action="menu.php">
<div class = 'cont'>
<span>item_name</span>
<hr />
<img id='img_order' src='img/$item_pic' alt='ss'>
<p id='price'>price : 3.14 </p>
<p id='bio'>this item is ... </p>
<input type= 'submit' class='btn btn-primary' value='Add to Order' name = 'order' />
</div>
and in the "menu.php"
if(isset($_POST['addToDatabase'])){
quert = "INSERT INTO table_name('item_id','item_name','item_price','item_bio' )VALUE('$item_id' , '$item_name','item_price','item_bio')";
}
How store the item_id , item_name , item_price and item_bio in variables and put in values to send the database ?
Note : don't care about syntax if thes code is not running
I just want tell me answer the quastion
With them html Form like this
<form method="POST" action="menu.php">
<div class='cont'>
<span><input type="text" name="item_name" value ="item name" readonly/></span>
<hr />
<img id='img_order' name="img_order" src='img/$item_pic' alt='ss'>
<p id='price'>price : <input type="text" name="item_price" value="3.14" readonly/> </p>
<p id='bio'><textarea name="address" rows="5" cols="40" readonly>This item is ...</textarea></p>
<input type="hidden" name="item_id" value="itemid" />
<input type='submit' class='btn btn-primary' value='Add to Order' name='addToDatabase' />
</div>
And your php code would look like this for pdo prepared Statements and a established Connection
db.php
<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'root';
$password = '0000';
try {
$pdo = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
It is recommended to put the db.php file in a subfolder, so please do that and edit the require accordingly
and the php file that uses the send data
<?php
require ('db.php');
if(isset($_POST['addToDatabase'])){
$stmt = $pdo->prepare("INSERT INTO table_name('item_id','item_name','item_price','item_bio' )
VALUE( (?, ?,?, ?)");
$stmt->execute([$_POST['item_id'], $_POST['item_name'],$_POST['item_price'],$_POST['item_bio']]);
$stmt = null;
}
?>
I have an application where a user can send request edit to the admin, now the problem is how to store the id of the requested asset from user_asset table to the request table so I can display it to the admin's page with full details of the asset
when the user clicks on the request edit he gets a form with editable fields filled with current information but how can I store this asset's id so I can fetch it to the admin's table with information from both tables (user_assets, requests)
I have user_asset table
asset_id
asset_category
code
title
userid
and requests table
id
reason
assetid
user_id
this is what I have done so far
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
?>
and this is my form
<form method="post" action="req_ade.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
these are the errors I'm getting
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Incorrect integer value: '' for column 'assetid' at row 1' in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
( ! ) mysqli_sql_exception: Incorrect integer value: '' for column 'assetid' at row 1 in D:\wamp64\www\Caprabia-test\req_ade.php on line 37
Notice: Undefined index: id in D:\wamp64\www\Caprabia-test\req_ade.php on line 28
There is no "id" in your $_GET array. So your $asset_id variable will be empty and a empty string is not a valid int number. You should add (int) in your query:
mysqli_query($conn, "INSERT INTO `requests`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". (int)$asset_id ."','" .$_SESSION['user_id'] . "')")
Or better check the the $_GET array before you use it. Like this:
If(isset($_GET['id']))
{
$asset_id = mysqli_real_escape_string($conn, $_GET['id']);
}
else
{
...
}
Thank you for all your suggestions.
After trying a lot of suggestions and manipulating with the code I have found a solution for it.
if(isset($_POST['submit'])){
// get all values from input with no special charactere
$code = mysqli_real_escape_string($conn, $_POST['code']);
$asset_id = mysqli_real_escape_string($conn, $_POST['asset_id']);
$reason = mysqli_real_escape_string($conn, $_POST['reason']);
if (!$error) {
if (!$error) {
// execute the sql insert
if(mysqli_query($conn, "INSERT INTO `requests1`(id,reason,assetid, user_id)
VALUES( null, '" . $reason . "', '". $asset_id ."','" .$_SESSION['user_id'] . "')")) {
// if the insert result was true (OK)
$success_message = "req was successfully added ! ";
} else {
// if the insert result was false (KO)
$error_message = "Error in data...Please try again later!";
}
}
}
}
else{
if(isset($_GET['idedit']) ){
$result = mysqli_query($conn, "SELECT * from user_asset WHERE asset_id=".$_GET['idedit']);
$project = mysqli_fetch_array($result);
}
}
and this is the form I have posted the asset_id in a hidden type
<form method="post" action="req_ade1.php" id="adding_new_assets">
<div class="control-group">
<label for="basicinput">الکود : </label>
<div class="controls">
<input type="hidden" value="<?php echo $project['asset_id'];?>" name="asset_id" />
<input type="number" id="basicinput" value="<?php echo $project['code']; ?>" placeholder="الكود" name="code" class="span8">
</div>
</div>
<div class="control-group">
<label for="basicinput">التفاصيل : </label>
<div class="controls">
<input type="text" id="basicinput" value="<?php echo $project['title']; ?>" placeholder="التفاصيل" name="title" class="span8">
</div>
</div>
<div>
<label style="color:black">السبب</label>
<textarea rows="8" cols="8" name="reason" class="form-control" placeholder="اذكر سبب التعديل ..." ></textarea>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="submit" class="btn">طلب تعديل</button>
</div>
</div>
</form>
I'm having issues with a PHP form that is using the isset() function for input values that have been pulled from a database. When I use the below code, the isset function is returning nothing to the input fields on an edit client form. I'm in need of some help on how I can get this head scratching problem solved.
edit-client.php
<?php
require_once __DIR__ . '/inc/bootstrap.php';
require_once __DIR__ . '/inc/head.php';
require_once __DIR__ . '/inc/nav.php';
$client = getClient(request()->get('client_id'));
$firstName = $client['first_name'];
$lastName = $client['last_name'];
$notes = $client['notes'];
$buttonText = 'Update Client';
?>
<div class="container-fluid">
<div class="row">
<?php include __DIR__ . '/inc/sidebar-nav.php'; ?>
<main role="main" class="col-md-9 ml-sm-auto mt-4 col-lg-10 px-4 main">
<h1 class="h3 border-bottom pb-3 mb-4 text-primary">Edit Client</h1>
<form method="post" action="/procedures/procedure-edit-client.php">
<label for="first_name" class="text-muted">First Name</label>
<input type="hidden" name="first_name" value="<?php if(isset($firstName)) echo $firstName; ?>">
<label for="last_name" class="text-muted">Last Name</label>
<input type="text" id="last_name" name="last_name" class="form-control" value="<?php if(isset($lastName)) echo $lastName; ?>" required>
<label for="notes" class="text-muted">Notes</label>
<textarea id="notes" name="notes" class="form-control" rows="10"><?php if(isset($firstName)) echo $firstName; ?></textarea>
<button type="submit" class="btn btn-action btn-primary">
<?php
if(isset($buttonText)) echo $buttonText;
else echo 'Add New Client';
?>
</button>
</form>
</main>
</div>
</div>
<?php require_once __DIR__ . '/inc/footer.php';
functions.php
function getClient($clientId) {
global $db;
try {
$query = "SELECT * FROM client WHERE client_id = ?";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $clientId);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(\Exception $e) {
throw $e;
}
}
Try this i assume you only get one result so returning that first result:
function getClient($clientId) {
global $db;
try {
$query = "SELECT * FROM client WHERE client_id = ?";
$stmt = $db->prepare($query);
$stmt->bindParam(1, $clientId);
$stmt->execute();
$result = $stmt->fetchAll();
return (!empty($result)) ? $result[0] : false;
} catch(\Exception $e) {
throw $e;
}
}
After that check you var_dump($client) again to see your data. Also when client is false, it could not find the client. Adjust your code to check for that also else $client is still empty.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 5 years ago.
Here I have a form:
<form action="includes/Payment.inc.php" method="get" class="px-4 py-4" >
<div class="form-group">
<div class="d-inline py-1"><h5>Payment Type</h5></div>
<select class="bg-white text-dark" name="payment_type">
<option value="Type">Type</option>
<option value="Food">Food</option>
<option value="House-Rent">House-Rent</option>
<option value="Other">Other</option>
</select>
<h5 class="py-1">Amount of Money</h5>
<div class="input-group">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="amount" aria-label="Text input with checkbox">
<span class="input-group-addon">JPY</span>
</div>
<h5 class="py-1">Detail</h5>
<textarea placeholder="Enter The Detail in here" name="detail"></textarea><br>
<label><h5 class="py-1">Date: </h5></label>
<input type="date" name="date"><br>
<button type="submit" name="submit" class="btn btn-primary m-4 border rounded">Submit</button>
</div>
</form>
When clicked simply put all the information into database with following PHP code:
<?php
if (isset($_GET['submit'])) {
include_once 'dbh.inc.php';
$payment_type = $_GET['payment'];
$amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
$detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
$date = $_GET['date'];
if (empty($amount_money)) {
header('Location: ../Data.php?money_empty');
exit();
}
else {
$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
VALUES (':payment_type',':amount',':detail',':payment_date')";
$result = $conn->prepare($sql);
$result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
$result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
$result->bindParam(':detail',$detail,PDO::PARAM_STR);
$result->bindParam(':payment_date',$date,PDO::PARAM_STR);
$result->execute();
header("Location: ../Data.php?payment_success");
exit();
}
}
Then when I test the form, the execution is completed but when I checked the "payment" table, here's what i got:
payment_type(varchar) = ":payment_type"
amount(int) = 0
detail(varchar) = ":detail"
payment_date(date) = "0000-00-00".
What's wrong with my code ??
In your code, you use '' to eclosed the string part in insert parameters this not need with PDO. Use the following instead...
<?php
if (isset($_GET['submit'])) {
include_once 'dbh.inc.php';
$payment_type = $_GET['payment'];
$amount_money = filter_input(INPUT_GET,'amount',FILTER_SANITIZE_NUMBER_INT);
$detail = filter_input(INPUT_GET,'detail',FILTER_SANITIZE_STRING);
$date = $_GET['date'];
if (empty($amount_money)) {
header('Location: ../Data.php?money_empty');
exit();
}
else {
$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
VALUES (:payment_type,:amount,:detail,:payment_date)";
$result = $conn->prepare($sql);
$result->bindParam(':payment_type',$payment_type,PDO::PARAM_STR);
$result->bindParam(':amount',$amount_money,PDO::PARAM_INT);
$result->bindParam(':detail',$detail,PDO::PARAM_STR);
$result->bindParam(':payment_date',$date,PDO::PARAM_STR);
$result->execute();
header("Location: ../Data.php?payment_success");
exit();
}
}
You are quoting your parameter markers, eg ':payment_type', which makes them look like plain strings to PDO, so those strings are what show up in the DB. As the docs show, you should not quote them:
$sql = "INSERT INTO payment(payment_type,amount,detail,payment_date)
VALUES (:payment_type, :amount, :detail, :payment_date)";
I am working on a web back-end that will pull information into a form, and then when updated, will update the database with the new information. However, when I try to pull information previously stored in a class private variable, it throws me an error stating that the information is NULL. What am I doing wrong here?
<?php
class modify_racer
{
private $mysqli, $racer_id, $firstname,
$lastname, $banner, $bio;
public function error($code)
{
switch($code)
{
case 1:
echo '<p id="error"><b>Error:</b> Please fill out all fields!</p>';
modify_racer::send_form($this->firstname, $this->lastname, $this->banner, $this->bio);
break;
case 2:
echo '<p id="error"><b>Error:</b> Racer already exists!</p>';
break;
case 3:
echo '<p id="error"><b>Error:</b> Could not connect to MySQLi: ' . mysqli_error();
break;
}
}
public function send_form($modify = 1)
{
?>
<div id="form">
<h3>Edit Racer:</h3>
<form method="post" action="">
<label for="firstname">First Name: </label>
<input type="text" id="firstname" name="firstname"
placeholder="Racer's First Name"
value="<?php echo $this->firstname;?>" />
<br />
<label for="lastname">Last Name: </label>
<input type="text" id="lastname" name="lastname"
placeholder="Racer's Last Name"
value="<?php echo $this->lastname;?>" />
<br />
<label for="banner">Banner Location: </label>
<input type="text" id="banner" name="banner"
placeholder="Racer's Banner Image Location:"
value="<?php echo $this->banner;?>" />
<br />
<label for="bio">Racer's Bio Info: </label>
<textarea rows="5" cols="50" id="bio" name="bio"
placeholder="Racer Statistics / Biography"
value=""><?php echo $this->bio;?></textarea>
<input type="submit" id="submit" name="modify" value="submit" />
</form>
</div>
<?php
}
public function get_racer($racerID)
{
$this->racer_id = $racerID;
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_info = "SELECT * FROM ArtecRacers WHERE RacerID=?";
$load_racer = $this->mysqli->prepare($racer_info);
$load_racer->bind_param('s', $racerID);
$load_racer->execute();
$load_racer->bind_result($this->racerID, $this->firstname, $this->lastname, $this->banner, $this->bio);
$load_racer->fetch();
modify_racer::send_form();
}
public function list_racers()
{
?>
<div id="form">
<h3>Select Racer:</h3>
<form method="post" action="">
<?php
$this->mysqli = new mysqli(MYSQLI_HOST,MYSQLI_USER,MYSQLI_PASS,MYSQLI_DATABASE)
or die(error(3));
$racer_list = "SELECT * FROM ArtecRacers";
$get_racers = $this->mysqli->query($racer_list);
while($list = $get_racers->fetch_array(MYSQLI_NUM))
{
echo '<input id="part" type="radio" name="editRacer" value="' . $list[0] . '"/>';
echo '<label for="part">' . $list[1] . ' ' . $list[2] . '</label><br />';
}
?>
<input type="submit" name="selectRacer" id="submit" value="Select Racer" />
</form>
</div>
<?php
}
function test2()
{
echo $this->firstname;
echo $this->lastname;
echo $this->racer_id;
}
}
$start = new modify_racer();
if(!isset($_POST['selectRacer']))
$start->list_racers();
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
$start->test2();
?>
Everything in the code works except at $start->test2(); all of the information pulled from the function test2() is blank, and I am not sure why... Any insights?
EDIT:
I changed the code to reflect the following on the bottom, and test2() still outputs the variables as NULL:
if(!isset($_POST['editRacer']))
$start->list_racers();
else
$start->get_racers($_POST['editRacer']);
$start->test2();
If you leave your code alone, you're going to have to pass both selectRacer and editRacer parameters into the page. My guess is that you might only want to pass the one, though. In which case, you'll want to change
if(isset($_POST['selectRacer']))
$start->get_racer($_POST['editRacer']);
into
if(isset($_POST['editRacer']))
$start->get_racer($_POST['editRacer']);
Also, if you want to pass these values in through the URL bar, you need to check $_GET, not $_POST.
And finally, everywhere that you are making method calls by executing modify_racer::my_method_here(), you should change that to $this->my_method_here(). The former is a static method call, meaning it's not actually associated with your object, meaning it can't touch those variables. For it to be able to access and change the variables, you'll need to call it through $this.