php - Add Script Not working - php

I'm having a problem with my update script. Basically I enter values into textboxes and when I click on 'Add' these values get added to the database.
At the moment it is allowing me to enter intergers and these getting added to the database but when I try to add text it doesn't. The database field types are set to varchar(20) and this is my PHP code:
public function insert($tableName,$fieldArray,$fieldValues) {
$pdo = new SQL();
$dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);
$this->sql = "INSERT INTO " . $tableName . " (".implode(',', $fieldArray).") VALUES (".implode(',', $fieldValues).")";
try {
// Query
$stmt = $dbh->prepare($this->sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count.' row(s) inserted by SQL: '.$stmt->queryString;
$stmt->closeCursor();
}
catch (PDOException $pe) {
echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
die();
}
// Close connection
$dbh = null;
}
Please let me know what I am doing wrong! :)

Change the sql query line to:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`, `', $fieldArray)."`) VALUES ('".implode("', '", $fieldValues) . "')";
The thing is you are not escaping strings with quotes. Like 'someText'

You need to enclose your fields into quotes.
Put the text as such
$text = "text"; //How you're doing it now
$text = "'text'"; //How you ought to (after sql escaping)
Or try this:
$this->sql = "INSERT INTO " . $tableName . " (`".implode('`,`', $fieldArray)."`) VALUES ('".implode("','", $fieldValues)."')";

Related

php/pdo insert into database mssql with arrays

I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;

Query doesn't insert value into DB

In my query the update statement doesn't work, the error given is:
Number of parameter doesn't match with prepared statement
this is my code:
public function update_resource($resource)
{
$mysqli = new MySQLi(HOST, USERNAME, PASSWORD, DATABASE);
$this->connection_state($mysqli);
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
AND sigla = '$sigla' AND colore = '$colore' AND planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param("ssssi", $descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}
The code go into the Added condition but the query fail, what's the problem?
public function update_resource($resource)
{
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
, sigla = '$sigla', colore = '$colore', planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param($descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}?
Your problem is that you don't have any placeholders in your query.
Refer to manual to see how placeholders should be set.
In general, placeholders are ? which later will be replaced with values, so your query should look like:
$query = "UPDATE risorse SET descrizione = ?
AND sigla = ? AND colore = ? AND planning = ?
WHERE id = ?";
please visit on http://php.net/manual/en/pdostatement.bindparam.php.you got your answer.see Example #1 Execute a prepared statement with named placeholders

MySQL update, skip blank fields with PDO

I would like to update a MySQL row via the form below. The form works great as is but, if I leave a field blank, it changes the field in MySQL to blank as well. I would like to update the sql but skip over any fields that are blank.
I have read a few ways of doing this but they didn't seem logical. I.e. using if statements in the sql string itself. (Having MySQL do the work that should be done in PHP).
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<form method="post" action="">
ID: <input type="text" name="a" /><br>
Program: <input type="text" name="b" /><br>
Description: <textarea row="6" cols="50" name="c"></textarea><br>
Cost: <input type="text" name="d"><br>
<input type="submit" value="Add Link" />
</form>';
}
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
$stmt->bindParam(":id", $_POST["a"]);
$stmt->bindParam(":program", $_POST["b"]);
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->bindParam(":cost", $_POST["d"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Something like this should work
.
.
.
$q = array();
if(trim($_POST["b"]) !== ""){
$q[] = "Program = :program";
}
if(trim($_POST["c"]) !== ""){
$q[] = "Descr = :descr";
}
if(trim($_POST["d"]) !== ""){
$q[] = "Cost = :cost";
}
if(sizeof($q) > 0){//check if we have any updates otherwise don't execute
$query = "UPDATE links SET " . implode(", ", $q) . " WHERE Id= :id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(":id", $_POST["a"]);
if(trim($_POST["b"]) !== ""){
$stmt->bindParam(":program", $_POST["b"]);
}
if(trim($_POST["c"]) !== ""){
$stmt->bindParam(":descr", $_POST["c"]);
}
if(trim($_POST["d"]) !== ""){
$stmt->bindParam(":cost", $_POST["d"]);
}
$stmt->execute();
}
.
.
.
Change the statement:
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
As follows:
$stmt = $dbh->prepare('UPDATE links SET Program = IF(trim(:program)="", Program, :program) , Descr = IF(trim(:descr)="", Descr, :descr), Cost = IF(trim(:cost)="", Cost, :cost) WHERE Id= :id');
Check post field for empty :
It will skip update query if any field data is empty.
If( $_POST["a"] && $_POST["b"] && $_POST["c"] && $_POST["d"]){
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare('UPDATE links SET Program = :program , Descr = :descr, Cost = :cost WHERE Id= :id');
$stmt->bindParam(":id", $_POST["a"]);
$stmt->bindParam(":program", $_POST["b"]);
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->bindParam(":cost", $_POST["d"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Option2 Update all fields except empty:
try {
$sql ="UPDATE links SET ";
if($_POST["a"])
$sql .=" Program = :program ,";
if($_POST["b"])
$sql .=" Descr = :descr ,";
if($_POST["c"])
$sql .=" Cost = :cost ,";
$sql = rtrim($sql,',');
$dbh = new PDO($dsn, $user, $pass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $dbh->prepare($sql);
if($_POST["a"])
$stmt->bindParam(":id", $_POST["a"]);
if($_POST["b"])
$stmt->bindParam(":program", $_POST["b"]);
if($_POST["c"])
$stmt->bindParam(":descr", $_POST["c"]);
$stmt->execute();
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());}
$dbh = null;
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
It is easier to use unnamed parameters for dynamic queries in PDO and passing them as an array in execute(). The statement will not be executed unless at least 1 parameter is passed along with the id. I have left in the echo of the derived statement and the dump of the array.
Example statement
UPDATE `links` SET `Program` = ? , `Cost` = ? WHERE `Id` = ?
Example array
Array ( [0] => 2 [1] => 3 [2] => 2 )
if(isset($_GET['a'])){
$id = $_GET['a'];
$program = isset($_GET['b']) ? $_GET['b'] : NULL;
$descr = isset($_GET['c']) ? $_GET['c'] : NULL;
$cost= isset($_GET['d']) ? $_GET['d'] : NULL;
$params =array();
$sql = "UPDATE `links` SET "; //SQL Stub
if (isset($program)) {
$sql .= " `Program` = ? ,";
array_push($params,$program);
}
if (isset($descr)) {
$sql .= " `Descr` = ? ,";
array_push($params,$descr);
}
if (isset($cost)) {
$sql .= " `Cost` = ? ,";
array_push($params,$cost);
}
$sql = substr($sql, 0, -1);//Remove trailing comma
if(count($params)> 0){//Only execute if 1 or more parameters passed.
$sql .= " WHERE `Id` = ? ";
array_push($params,$id);
echo $sql;//Test
print_r($params);//Test
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
}
}

How to check if there is value or not using MySQL/PHP

Well here is the script:
<?php
session_start();
$con = mysql_connect("localhost","***","***");
mysql_query("SET NAMES UTF8");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("**8", $con);
$sql = mysql_query("TRUNCATE TABLE headset");
$qry= "INSERT INTO `headset` (`WebTitle`) VALUES ('". $_POST[webtitle] ."')";
$sql = mysql_query("TRUNCATE TABLE headset2");
$qry= "INSERT INTO `headset2` (`WebSlogan`) VALUES ('". $_POST[webslogan] ."')";
if (!mysql_query($qry,$con))
{
die('Error: ' . mysql_error());
}
header("location: ../generalsettings.php");
exit();
mysql_close($con);
?>
This is just for the one value:
I have a form with 2 boxes and I want to achieve the following: if only one of the boxes is filled I would like to truncate and insert only the value that is filled, and do nothing with the other unfilled box.
I hope you got my point.
Don't use the mysql_query functions!!! Better use the pdo class
http://php.net/manual/de/book.pdo.php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
if (isset($_POST['webtitle']) && $_POST['webtitle'] != '') {
try {
$db->query('TRUNCATE TABLE headset');
$stmt = $db->prepare("INSERT INTO headset (WebTitle) VALUES (?)");
$stmt->bindParam(1, $_POST[webtitle]);
$stmt->execute();
} catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
}
}
to check if there is value in database do this
$myquery= mysql_query(" select * from headset ");
if(mysql_fetch_row($myquery)==0){ --//there is no data in your database
}
else { --//there is data do what you like
}
*please use mysqli or PDO instead of mysql
if (isset($_POST['webtitle']) && $_POST['webtitle'] != '') {
// $_POST['webtitle'] code here
}
if (isset($_POST['webslogan']) && $_POST['webslogan'] != '') {
// $_POST['webslogan'] code here
}
And the same for the other one

JSONKit - parse JSON String to PHP to MYSQL database

In my database I have the following schema:
Answers:
answerId(PK) auto_inc
answer
questionId
I am passing the following JSON String to my php file:
[{"answer":"bnk","questionId":"1"},{"answer":"1","questionId":"2"},{"answer":"b n","questionId":"3"},{"answer":"3","questionId":"4"},{"answer":"rgb","questionId":"5"},{"answer":"No","questionId":"6"},{"answer":"0","questionId":"7"},{"answer":"0","questionId":"8"},{"answer":"0","questionId":"9"},{"answer":"0","questionId":"10"},{"answer":"0","questionId":"11"},{"answer":"0","questionId":"12"},{"answer":"0","questionId":"13"},{"answer":"0","questionId":"14"},{"answer":"3","questionId":"18"},{"answer":"nko","questionId":"19"},{"answer":"hhkl","questionId":"15"},{"answer":"2","questionId":"16"},{"answer":"vnlf hugg","questionId":"17"}]
This is captured via a post request in $_POST['answers']:
if(isset($_POST['submitanswer'])){
$dbh = connect();
$user = $_POST['user'];
$entry = $_POST['entryId'];
$answers = $_POST['answers'];
$answers = json_decode($answers); //decode JSON answers
//for loop to iterate through answers ans insert new row into database
}
How do I iterate through the answers array and insert a new row into my answers table?
Something like:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
mysql_query($query);
}
If this code didn't work for you, try this:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
mysql_query($query);
}
Otherwise, I can't spot anything wrong here.
I gues you know this but make sure your connection string is good.
Actually this is what I do. Probably a bit much info for you, also I do all that concatenation in the SQL so I can easily comment out fields for testing.
$Link = mysql_connect( $Host , $User , $Password , $DBName);
if (!$Link) {
die('Could not connect: ' . mysql_error());
}
$sql = "insert into table "
."("
."hashfirstName".","
."hashfamilyName".","
."hashemailAddress"
.")"
."values ("
."'$firstNameHashed'".","
."'$familyNameHashed'".","
."'$emailAddressHashed'"
.")";
mysql_select_db($DBName , $Link) or die("Database error in insertdata<br>"."Error #" . mysql_errno() . ": " . mysql_error());
if(!mysql_query($sql , $Link))
{
$errors['sql'] = $sql;
$errors['DBName'] = $DBName;
$errors['Link'] = $Link;
$errors['status'] = "false"; //There was a problem saving the data;
echo json_encode($errors);
}
else
{
$errors['status'] = "true";
echo json_encode($errors);
}; // if(!mysql_query( $DBName , $sql , $Link))

Categories