Cannot bind date value using bindvalue function with PDO::PARAM_STR - php

So, I cannot find the solution to the problem I'm having. I'm really new to coding but learned how to start coding using basic HTML, PHP, PDO, and AJAX. So my problem comes from a form that retrieves dates from a calendar using the type=date from the form. The code of the form is down below.
<div class="col-lg-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title text-center"><i class="fa fa-bar-chart fa-fw"></i> Ingreso de reporte</h3>
</div>
<div id="alert_success" class="panel-body">
<br>
<form method="post" class="form-horizontal" role="form" action="ajax_form_post.php" id="insertreport">
<div class="form-group">
<label class="control-label col-sm-2" for="video" style="color:#777;">ID de video</label>
<div class="col-sm-10">
<input type="text" name="video" class="form-control" id="video" placeholder="Ingresa id del video" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date_i" style="color:#777;">Fecha de arriendo</label>
<div class="col-sm-10">
<input type="date" name="date_i" class="form-control" id="date_i" placeholder="" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date_f" style="color:#777;">Fecha de devolución</label>
<div class="col-sm-10">
<input type="date" name="date_f" class="form-control" id="date_f" placeholder="" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="hidden" name="c_id" class="form-control" id="user_id" value="<?php echo $id ?>" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" name="update_customer" value="Enviar" id="submitdata">
</div>
</div>
</form>
<div class="text-right">
<i class="fa fa-arrow-circle-right"></i>
</div>
</div>
</div>
</div>
Now the problem starts with this Ajax form I built. BTW the script is working fine, the problem is inside this set of code.
<?php
/****************Get customer info to ajax *******************/
//require database class files
require("includes/pdocon.php");
//instatiating our database objects
$db = new Pdocon ;
if(isset($_POST['c_id'])){
$id = $_POST['c_id'];
$date_i = date("Y-m-d", strtotime($_POST['date_i']));
$date_f = date("Y-m-d", strtotime($_POST['date_f']));
$raw_v_id = clean_data($_POST['video']);
$v_id = val_int($raw_v_id);
$db->query('SELECT * FROM videos WHERE v_id = :v_id');
$db->bindvalue(':v_id', $v_id, PDO::PARAM_INT);
$row = $db->fetchSingle();
$db->query('INSERT INTO arriendo (transaccion, c_id, v_id, f_arriendo, f_devolucion)
VALUES (NULL, :c_id, :v_id :f_arriendo, :f_devolucion)');
$db->bindvalue(':f_arriendo', $date_i, PDO::PARAM_STR);
$db->bindvalue(':f_devolucion', $date_f, PDO::PARAM_STR);
$db->bindvalue(':c_id', $id, PDO::PARAM_INT);
$db->bindvalue(':v_id', $v_id, PDO::PARAM_INT);
$run = $db->execute();
}
if($run){
echo "<p class='bg-success text-center' style='font-weight:bold;'>Valor actualizado </p>";
}
?>
I get the following error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''2021-08-05', '2021-08-06')' at line 2
Any help or a little guidance would be greatly appreciated. Thanks in advance.

Related

Bind param not working

I'm trying to update informations in my database
this is the html page:
<form method="post" action="update.php">
<fieldset>
<legend>Modifier informations:</legend>
<div class="row">
<div class="col-sm-3">
<label class="form-control">Nom</label>
</div>
<div class="col-sm-9">
<input class="form-control" type="text" name="title">
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label class="form-control">Adresse</label>
</div>
<div class="col-sm-9">
<input class="form-control" type="text" name="adresse">
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label class="form-control">Date fe FONDATION</label>
</div>
<div class="col-sm-9">
<input class="form-control" type="date" name="date_creation">
</div>
</div>
<div class="row">
<div class="col-sm-3">
<label class="form-control">Détails</label>
</div>
<div class="col-sm-9">
<textarea class="form-control" name="details"></textarea>
</div>
</div>
<br>
<button style="float: right" type="submit" class="btn btn-primary">Valider</button>
</div>
</fieldset>
</form>
</div>
this is update.php
<?php
require "DB/config.php";
include "Service/Association.php";
/*require '../connected.php';*/
session_start();
$ASS = new Association("1",$_POST["title"],$_POST["adresse"],$_POST["details"],$_POST["date_creation"]);
$c=new config();
$conn = $c->getConnexion();
$ASS->ModifierAssociation($ASS,$conn);
and this is the method in my association class:
function ModifierAssociation($Animaux,$conn){
try {
$stmt = $conn->prepare("update `association`( `nom`, `adresse`, `details`, `date_creation` )VALUES(:nom,:adresse,:details,:date_creation)");
$nom=$Animaux->getnom();
$stmt->bindParam(':nom',$nom);
$adresse=$Animaux->getadresse();
$stmt->bindParam(':adresse',$adresse);
$details=$Animaux->getdetails();
$stmt->bindParam(':details',$details);
$date_creation=$Animaux->getdate_creation();
$stmt->bindParam(':date_creation',$date_creation);
print_r($stmt);
$stmt->execute();
}catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
}
i get this error
PDOStatement Object ( [queryString] => update association( nom, adresse, details, date_creation )VALUES(:nom,:adresse,:details,:date_creation) )
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '( nom, adresse, details, date_creation )VALUES('1','','','')' at line 1
The syntax for MySQL UPDATE is:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
So you need:
$stmt = $conn->prepare(
"UPDATE `association` SET
`nom` =:nom,
`adresse` = :adresse,
`details` = :details,
`date_creation` = :date_creation");
Note this will update the entire association table so you should identify the rows you want to update with the WHERE clause.

Form in a bootstrap modal doesn't insert data in MySQL

I'm trying to insert data to MySQL with a form that is in a Bootstrap modal but it doesn't work.
I don't know why but my form method is POST and it seems to be a GET because it prints the data in the web address.
When I try to insert the data through a basic form with the same php code (no format, simple as hell) it inserts the data.
Here's my form in the bootstrap modal.
<div class="container 2">
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal" data-target="#newRoute">
CREAR NUEVA RUTA
</button>
<div class="modal fade" id="newRoute" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<form class="route" method="post">
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
<label for="name">Ponle un nombre a la ruta</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group">
<label for="city">Ciudad</label>
<input type="text" class="form-control" id="city" name="city" required>
</div>
<div class="form-group">
<label for="length">Distancia</label>
<input type="text" class="form-control" id="length" name="length" required>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
<label for="start_point">Punto de salida</label>
<input type="text" class="form-control" id="start_point" name="start_point"
required>
</div>
<div class="form-group">
<label for="difficulty">Dificultad</label>
<input type="text" class="form-control" id="difficulty" name="difficulty"
required>
</div>
<div class="form-group">
<label for="date">Fecha de la ruta</label>
<input type="date" class="form-control" id="date" name="date" required>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<label for="description">Detalles de la ruta</label>
<textarea class="form-control" rows="5" id="description"
name="description"></textarea>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<button type="submit" name="submit" id="submit" class="btn btn-primary"
value="Enviar">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
and here is my PHP code
include('db/db.php');
if(isset($_POST['submit'])) {
// Adjudicar name a variable
$name = stripslashes($_POST['name']);
$name = mysqli_real_escape_string($conn, $name);
// Adjudicar city a variable
$city = stripslashes($_POST['city']);
$city = mysqli_real_escape_string($conn, $city);
// Adjudicar length a variable
$length = stripslashes($_POST['length']);
$length = mysqli_real_escape_string($conn, $length);
// Adjudicar start_point a variable
$start_point = stripslashes($_POST['start_point']);
$start_point = mysqli_real_escape_string($conn, $start_point);
// Adjudicar difficulty a variable
$difficulty = stripslashes($_POST['difficulty']);
$difficulty = mysqli_real_escape_string($conn, $difficulty);
// Adjudicar date a variable
$date = stripslashes($_POST['date']);
$date = mysqli_real_escape_string($conn, $date);
// Adjudicar description a variable
$description = stripslashes($_POST['description']);
$description = mysqli_real_escape_string($conn, $description);
// QUERY
$query = "INSERT INTO routes (name, city, length, start_point, difficulty, user_id, date, description) VALUES ('$name','$city',$length,'$start_point','$difficulty',".$_SESSION['id'].",'$date','$description')";
// Se realiza la query
$result = mysqli_query($conn,$query);
//Condición si se realiza la query correctamente
if($result){
header("Location: routes.php");
echo '<script type="text/javascript">alert("'.$query.'");</script>';
}else{
echo '<script>alert("ERROR");</script>';
}}
my db.php (connection to database)
$conn = new mysqli('localhost', 'root', "", 'users');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Thanks in advance!
PS. When I submit the form, this is what appears in the address (all the fields were filled by sample text). It seems to be a get form.
http://localhost/Proyecto/routes.php?name=Test&city=Test&length=20&start_point=Test&difficulty=Test&date=2018-05-12&description=Test+description&submit=Enviar
Try to check if you have forget to close any other form somewhere on your code that should be with method="get" or without method attribute
and so when you submit the data it gets the method from that form.
The code you have publish here should work correctly.
Your form code is correct, I have checked it on my system. You must be checking/testing some other page or form.

Inserting data into MySQL server

I'm doing a e-commerce admin panel and I need a quick script for inserting data into MySQL. Here's what i've done and it does nothing.
<form action="#" id="form_sample_1" class="form-horizontal" method="post">
<div class="control-group">
<label class="control-label">Package Name<span class="required">*</span></label>
<div class="controls">
<input type="text" name="pkg_name" data-required="1" class="span6 " value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Package Price <span class="required">*</span><small>(In Dollars)</small></label>
<div class="controls">
<input name="pkg_price" type="number" class="span6 " value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Package Contains</label>
<div class="controls">
<input name="pkg_contains" type="text" class="span6 " value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Your Password</label>
<div class="controls">
<input name="sifre" type="password" class="span6 " value=""/>
</div>
</div>
<div class="form-actions">
<button type="button"name="btn" class="btn btn-primary">Send request to server.</button>
</div>
</form>
<!-- END FORM-->
</div> <!--widget box light-grey end-->
<!-- Mass PHP starts here! -->
<?php
echo mysql_error();
include("include/baglan.php");
// set posts here.
$_POST['pkg_name'] = $pkg_name;
$_POST['pkg_price'] = $pkg_price;
$_POST['pkg_contains'] = $pkg_contains;
$sifre = mysql_real_escape_string(md5($_POST['sifre']));
if($_POST['btn'] and $_POST["sifre"] = $sifre){
mysql_query("INSERT INTO packages (pkg_name, pkg_price,pkg_contains) VALUES $pkg_name $pkg_price $pkg_contains");
echo "Success.";
}
else {
echo mysql_error();}
It returns nothing! I've re-written all code but nothing! please help me. The databae variables are;
id, auto incerment
pkg_name text
pkg_price int
pkg_contains mediumtext
Assign variable name should be the left side.
// set posts here.
$pkg_name=$_POST['pkg_name'];
$pkg_price=$_POST['pkg_price'];
$pkg_contains=$_POST['pkg_contains'];
Values() is function, put all vars in bracket and split them with ','.
mysql_query("INSERT INTO packages (pkg_name, pkg_price,pkg_contains) VALUES($pkg_name,$pkg_price,$pkg_contains)");

write data to mysql

Here is my problem I tray to write data to mysql but when I do input
and press submit button, got console log message from function wich
mean everythig is ok, but when I look to db have nothing to see. Can
anyone help me.
Second thing what I need to do is SELECT data from that db, then
that data + new data from input = data save to db.
here is html code :
<div class="body-content bg-1">
<div class="col-sm-12 col-xs-12" ng-controller="UnosUSkladisteCtrl">
<div class="container">
<div class="alert alert-info alert-dismissable"><strong>Info!</strong> {{data.message}}</div>
<div class="center">
<h1>Ulaz robe u skladište</h1>
</div>
<p ng-controller="LoginCtrl">Dobro došao <b>{{deName}}</b> | <a id="logout" href ng-click="logout()">Odjava</a></p>
</div>
<div class="nav-button center col-sm-4 col-xs-4">Povratak</div>
<div>
<form class="form-horizontal col-xs-12" col-sm-12" name="signUpForm" ng-submit="submitFormSignUp()" novalidate>
<!-- Zlatni medvjed -->
<div class="form-group" ng-class="">
<label class="col-sm-4 col-xs-12 control-label no-padding-right " for="zlatni_medvjed">Zlatni medvjed boca 0.5l</label>
<div class="col-sm-4 col-xs-12">
<span class="block input-icon input-icon-right">
<input ng-model="zlatni_medvjed" placeholder="Količina boca 0.5l" type="number" class="form-control">
</span>
</div>
</div>
<!-- Crna kraljica -->
<div class="form-group" ng-class="">
<label class="col-sm-4 col-xs-12 control-label no-padding-right " for="crna_kraljica">Crna kraljica boca 0.5l</label>
<div class="col-sm-4 col-xs-12">
<span class="block input-icon input-icon-right">
<input ng-model="crna_kraljica" placeholder="Količina boca 0.5l" type="number" class="form-control">
</span>
</div>
</div>
<!-- Grička vještica -->
<div class="form-group" ng-class="">
<label class="col-sm-4 col-xs-12 control-label no-padding-right " for="gricka_vjestica">Grička vještica boca 0.5l</label>
<div class="col-sm-4 col-xs-12">
<span class="block input-icon input-icon-right">
<input ng-model="gricka_vjestica" placeholder="Količina boca 0.5l" type="number" class="form-control">
</span>
</div>
</div>
<!-- Dva klasa -->
<div class="form-group" ng-class="">
<label class="col-sm-4 col-xs-12 control-label no-padding-right " for="dva_klasa">Dva klasa boca 0.5l</label>
<div class="col-sm-4 col-xs-12">
<span class="block input-icon input-icon-right">
<input ng-model="dva_klasa" placeholder="Količina boca 0.5l" type="number" class="form-control">
</span>
</div>
</div>
<!-- SUBMIT BUTTON -->
<label class="col-sm-4 control-label no-padding-right"></label>
<div class="col-sm-4">
<button ng-click="insertdata()" type="submit" class="btn btn-primary btn-lg btn-block">Unesi količine u skladište</button>
</div>
</form>
</div>
</div>
Here is js file code :
angular.module('angularLoginApp')
.controller('UnosUSkladisteCtrl', function($scope,$http) {
$scope.insertdata = function(){
$http.post("database/unos-piva.php", {'zlatni_medvjed':$scope.zlatni_medvjed, 'crna_kraljica':$scope.crna_kraljica, 'gricka_vjestica':$scope.gricka_vjestica, 'dva_klasa':$scope.dva_klasa })
.success(function(data,status,headers,config){
console.log("Podaci uspiješno spremljeni");
alert("Nove količine piva su dodane u skladište");
});
}
$scope.data = {message: "Molimo vas da točno navedete što unosite u skladište"};
});
and this is PHP file code to connect :
<?php
$data = json_decode(file_get_contents("php://input"));
$zlatni_medvjed = mysql_real_escape_string($data->zlatni_medvjed);
$crna_kraljica = mysql_real_escape_string($data->crna_kraljica);
$gricka_vjestica = mysql_real_escape_string($data->gricka_vjestica);
$dva_klasa = mysql_real_escape_string($data->dva_klasa);
mysql_connect("localhost","root","");
mysql_select_db("medvedgrad");
mysql_query("INSERT INTO stanje_piva(`zlatni_medvjed`, `crna_kraljica`, `gricka_vjestica`,`dva_klasa`)VALUES('"$zlatni_medvjed"','"$crna_kraljica"','"$gricka_vjestica"','"$dva_klasa"')")
?>
mysql columns
zlatni_medvjed, crna_kraljica, gricka_vjestica, dva_klasa
The format of the insert statement is wrong - you are incorrectly using quotes ( both single and double ) and the statement was not terminated with a semi-colon.
mysql_query("
INSERT INTO stanje_piva(`zlatni_medvjed`, `crna_kraljica`, `gricka_vjestica`,`dva_klasa`)
VALUES('{$zlatni_medvjed}','{$crna_kraljica}','{$gricka_vjestica}','{$dva_klasa}')
");
That said, this sql is vulnerable to sql injection and you are using the now deprecated mysql_* class - upgrade your code to mysqli or PDO and learn how to use Prepared Statements
As for the second question do an update stanje_piva ... set field=field+new data.... where id=1 etc ~ you would not need the initial select statement

sql update not executing

Apologies if there is another feed with this same problem, I have tried different suggested solutions but I still get an error, and I cant see why!
I want to update a row in my table using a html form. I have populated the form with the existing values, and want to be able to edit those and update them when the form is submitted, but I am getting this error:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'
in
/Applications/XAMPP/xamppfiles/htdocs/love-deals/admin/update_offer.php:46
Stack trace: #0
/Applications/XAMPP/xamppfiles/htdocs/love-deals/admin/update_offer.php(46):
PDOStatement->execute(Array) #1 {main} thrown in
/Applications/XAMPP/xamppfiles/htdocs/love-deals/admin/update_offer.php
on line 46
Here is the php / sql code:
if(isset($_POST['update'])) {
$updateTitle = trim($_POST['title']);
$updateDesc = trim($_POST['desc']);
$updateRedeem = trim($_POST['redeem']);
$updateStart = trim($_POST['start']);
$updateExpiry = trim($_POST['expiry']);
$updateCode = trim($_POST['code']);
$updateTerms = trim($_POST['terms']);
$updateImage = trim($_POST['image']);
$updateUrl = trim($_POST['url']);
$updateSql = 'UPDATE codes SET (title,description,redemption,start,expiry,textcode,terms,image,url) = (:title,:description,:redeem,:start,:exp,:code,:terms,:image,:url) WHERE id=:offerid';
$update = $db->prepare($updateSql);
$update->execute(array(':title'=>$updateTitle,':description'=>$updateDesc,':redeem'=>$updateRedeem,':start'=>$updateStart,':exp'=>$updateExpiry,':code'=>$updateCode,':terms'=>$updateTerms,':image'=>$updateImage,':url'=>$updateUrl,':id'=>$offerID));
}
and the html form:
<form id="update_offer" class="col-md-6 col-md-offset-3" method="post" action="update_offer.php?id=<?php echo $offerID; ?>">
<div class="form-group col-md-12">
<label class="col-md-12" for="title">Title</label>
<input id="title" class="form-control col-md-12" type="text" name="title" placeholder="Offer Title" value="<?php echo $title; ?>" required>
</div>
<div class="form-group col-md-12">
<label class="col-md-12" for="desc">Description</label>
<textarea id="desc" class="form-control col-md-12" name="desc" placeholder="Description" value="<?php echo $desc; ?>"></textarea>
</div>
<div class="form-group col-md-12">
<label class="col-md-12" for="redeem">Redemption</label>
<input id="redeem" class="form-control col-md-12" type="text" name="redeem" placeholder="Where to redeem" value="<?php echo $redeem; ?>" required>
</div>
<div class="form-group col-md-12">
<label class="col-md-12" for="start">Start Date</label>
<input id="start" class="form-control col-md-12" type="date" name="start" value="<?php echo $startDate->format('Y-m-d'); ?>" min="<?php echo date('Y-m-d') ?>" max="2021-12-31" required>
</div>
<div class="form-group col-md-12">
<label class="col-md-12" for="expiry">Expiry Date</label>
<input id="expiry" class="form-control col-md-12" type="date" name="expiry" value="<?php echo $expDate->format('Y-m-d'); ?>" min="<?php echo date('Y-m-d') ?>" max="2021-12-31" required>
</div>
<div class="form-group col-md-12">
<label class="col-md-12" for="code">Code</label>
<input id="code" class="form-control col-md-12" type="text" name="code" placeholder="Code (if applicable)" value="<?php echo $code; ?>">
</div>
<div class="form-group col-md-12">
<label class="col-md-12" for="terms">Terms</label>
<textarea id="terms" class="form-control col-md-12" name="terms" placeholder="Terms & Conditions" value="<?php echo $terms; ?>" required></textarea>
</div>
<div class="form-group col-md-12">
<label class="col-md-12" for="url">Offer URL</label>
<input id="url" class="form-control col-md-12" type="text" name="url" placeholder="Offer URL (if applicable)" value="<?php echo $url; ?>">
</div>
<div class="form-group col-md-12">
<label class="col-md-8" for="image">Image <img src="../images/offers/<?php echo $image; ?>" alt="" style="width: 200px;" /></label>
<input id="image" class="form-control col-md-4" type="file" name="image">
</div>
<div class="form-group col-md-12 pull-right">
<button id="update" type="submit" name="update" class="btn btn-primary"><i class="glyphicon glyphicon-refresh"></i> Update</button>
</div>
</form>
what am i doing wrong?! Im still learning php etc, so please be gentle, any help is much appreciated.
First, you have wrong syntax for update statement, as other guys mentioned already, change:
UPDATE codes SET (title,description,redemption,start,expiry,textcode,terms,image,url) = (:title,:description,:redeem,:start,:exp,:code,:terms,:image,:url) WHERE id=:offerid
Into
UPDATE `codes`
SET `title` = :title,
`description` = :description,
`redemption` = :redeem,
`start` = :start
`expiry` = :expiry
`textcode` = :code
`terms` = :terms
`image` = :image
`url` = :url
WHERE `id` = :offerid
Learn more about the SQL Update syntax here.
Then, one thing more you have a mistake in execute(). Change your :id into :offerid like below:
$update->execute(array(
':title' => $updateTitle,
':description' => $updateDesc,
':redeem' => $updateRedeem,
':start' => $updateStart,
':exp' => $updateExpiry,
':code' => $updateCode,
':terms' => $updateTerms,
':image' => $updateImage,
':url' => $updateUrl,
':offerid' => $offerID
));
You are using wrong syntax of Update
It would be
$updateSql = "UPDATE codes SET title =:title,
description =:description,
redemption =:redeem,
start =:start,
expiry =:exp,
textcode =:code,
terms :=terms,image =:image,
url =:url
WHERE id=:id";// write id instead of offset because you are binding ':id'=>$offerID
Check http://dev.mysql.com/doc/refman/5.7/en/update.html
thanks for your replies. My original update syntax was actually as you mentioned, I had changed it when looking through some other solutions, and not changed it back, but either way, even with correct syntax, I still got the same error.
Looking through your replies, I can see that I have ':id'=> $offerID but have used :offerid in the sql code, which obviously needs to be updated, so thanks for pointing that out! Hopefully that will fix the problem...

Categories