PDO update, no errors and no respons in DB - php

I am trying to update a specifik row in a table with no success or error message. I $_POST a form with many different inputs including one for selecting the specifik row(clubId).
I $_POST and use both name and value from my inputs in the form, handling these in the code below to make a query.
However, as I do not get any errormessage or can see anything wrong with my code except the security against injections I do not know where to proceed with this.
Do you see anything wrong with the code that could cause this? Otherwise, how should I proceed, tips, directions, new working code with the ability to handle forms without having to make any bigger change in the php code(Like I am trying below).
<?php
include ('../../db_conn.php');
$nameArrayValue = array();
foreach($_POST as $name => $value) {
if($name == 'clubId') {} else {
$nameArrayValue[] = $name." = :".$name;
}
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$values = implode(', ', $nameArrayValue);
$sql = "UPDATE random SET ".$values." WHERE id = :clubId";
$addRandom = $dbh->prepare( $sql );
foreach($_POST as $name => $value) {
$name = ":".$name;
$addRandom->bindParam($name, $value);
}
$addRandom->execute();
if($addRandom->rowCount() > 0) { echo' yaay'; }
//header('Location: ' . $_SERVER['HTTP_REFERER']);
?>

There where two errors in the code:
$addRandom->bindParam(:clubId, 199);
I had to remove the : before clubId and then change my value into a variable like below:
$addRandom->bindParam(clubId, $_POST['clubId']);
And now my code looks like:
include ('../../db_conn.php');
$nameArrayValue = array();
foreach($_POST as $name => $value) {
if($name == 'clubId') {} else {
if(!empty($value)) {
$nameArrayValue[] = $name." = :".$name;
}
}
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$names = implode(', ', $nameArray);
$values = implode(', ', $nameArrayValue);
$sql = "UPDATE random SET ".$values." WHERE id = :clubId";
$addRandom = $dbh->prepare( $sql );
foreach($_POST as $name => $value) {
if(!empty($value)) {
$addRandom->bindParam($name, $_POST[$name]);
$name = '';
}
}
$addRandom->execute();
if($addRandom->rowCount() > 0) { echo 'yaay'; }

Related

sqlsrv insert when columns vary

I have searched around the web but no luck.
Am new to SQLSRV and i was migrating from PHP MySQL to PHP SQL and am having trouble inserting data from a form as some fields are optional which makes the column number vary. I need help on how i can insert when the column number varies.
thank you
here is how my insert code looks like
// sql fields and values for main table
$in_fields = array();
$in_values = array();
// prepare insertion
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
}
}
// prepare sql stmt
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES ()";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}
The executeSql function looks like this
function executeSql($sql, $params) {
global $conndb;
$rs = sqlsrv_query($conndb, $sql, $params)or die("Db query error.<br />".print_r(sqlsrv_errors(), true));
return !$rs ? false : true;
}
You need to add placeholder values (?) in the VALUES part of your query, you will need a placeholder for every value you pass through - i.e. for every value in $in_values.
To do this you could have another array, that will just have a number of ? as values, and then, like you have done for the fields, implode the array into the VALUES. Like so:
$in_fields = array();
$in_values = array();
$placeholders = array(); // new array
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$value = sql_escape($value);
$in_fields[] = "[{$key}]";
$in_values[] = "'{$value}'";
// add a placeholder to the array
$placeholders[] = "?";
}
}
if (!empty($in_fields)) {
$sql = "INSERT into [table_name](";
$sql .= implode(", ", $in_fields);
$sql .= ") VALUES (" . implode(",", $placeholders) . ")";
if (executeSql($sql, $in_values)) {
$success = "Successfully Added New Record";
}
}

How to add mysqli_real_escape_string() to dynamic variables?

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>
I have this code and it works perfectly, however I want to add
mysqli_real_escape_string But how can I do that to each variable since I don't know there exact information? I want it before it gets added to the query incase special characters were added
I also realized that my id never changes, it always stays one, whats the problem with that?
Granted I do not have access to PHP right now I believe this should work and get you on prepared statements.
<?php
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$update_fields = array();
$bind_params_types = ''
$bind_params_values = array();
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$update_fields[] = '{$fieldname} = ?';
$bind_params_types .= 's';
$bind_params_values[] = $value;
}
}
$update_fields = implode(',', $update_fields);
$bind_params_values = implode(',', $value);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$update_fields} WHERE id= '$id'";
if($stmt = mysqli_prepare($conn, $query)){
$stmt->bind_param($bind_params_types,$bind_params_values);
$stmt->execute();
} else {
echo "failed";
}
}
}
I've done addon in your code before updation i've esacpe the string
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
$updatestr = mysqli_real_escape_string($conn, $updatestr);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>

How can I define which db to pull from via post

$value = $_POST['directions'];
$value2 = $_POST['inventory'];
$value3 = $_POST['item'];
$value4 = $_POST['vendor'];
$sql = "INSERT INTO a1 (directions,inventory,item,vendor) VALUE ('$value','$value2','$value3','$value4')";
Right now I'm having a mysql db get updated via what I type in a textbook from a separate page. However where it says "INSERT INTO a1" id like to make "a1" be a variable like "$table" I define from the same page I type all the other values in
The question need to be more clear, but from my understanding, you can use something like this code :
// should be defined like this inside each page.
$table = mysql_real_escape_string($_POST['tablename']);
$params = array();
foreach($_POST as $key => $val){
if($key!='tablename'){
$params[]= "$key='".mysql_real_escape_string($val)."'";
}
}
if(count($params) > 0) {
$params = implode(",",$params);
$sql = "INSERT INTO $table SET $params";
} else {
die "Error submitting the data!";
}

PHP insert with array values,tablename

I am struggling with a PHP insert statement. I want it to insert data into the database by using array_keys($values) and array_values($values).
I have tried to work out how I can do this and so far I have this code in my insert and have also included my index page. I need to do it without changing the index page as it is a challenge I have to complete. I have analysed the index page and need to somehow make the function work with that to insert data into my database from the PHP insert command.
I also wonder if there's a way to wrap the PDO connection into one statement which I can use for this and other functions.
Insert Function
<?php
function insert(array $values, $tablename)
{
//cosntruct sql statment
$sql = "INSERT INTO $tablename $values";
//pick apart vaules
//this line fetches the result set and fetch assoc to prevent multiple rows beign fetched
$ResultSet = dbconnect()->query($sql);
//returns the results
return $ResultSet;
//array keys and array vaules
//connection
// checks results
}
?>
Part of the Index page:
if(isset($_POST['table']))
{
$tableName = $_POST['table'];
}
if(isset($_POST['insert']))
{
$values = array();
$tableName = $_POST['tablename'];
foreach($_POST as $key => $value)
{
if(!empty($value) && ($value != "Submit") && ($key != "insert") && ($key != "table") && ($key != "tablename"))
{
$values[$key] = $value;
}
}
$count = insert($values, $tableName);
}
Note that I am quite new at coding. Any suggestions?
try this, it works fine for me. You just have to pass the name of the table and an associative array which has the name of the columns as keys.
public function insert($table, $data)
{
$query='INSERT INTO '.$table.' (';
foreach($data as $key => $value)
{
$query .= $key.',';
}
$query = substr($query, 0, -1);
$query .= ') VALUES (';
foreach($data as $key => $value)
{
$query .= ':'.$key.',';
}
$query = substr($query, 0, -1);
$query .= ');';
$insert = $this->db->prepare($query);
$insert->execute($data);
}

Posting Data to Multiple Columns into Mysql Database using PHP

So I'm trying to send 3 data values from an Arduino Mega to MySQL database using PHP for my senior design project but I'm encountering an issue. I found an example doing this with 1 data value that would also timestamp the data as it was received. For the life of me I can't figure out how to change the PHP code to pass through 3 values into 3 columns. Here is the PHP script for one data value being sent through:
<?php
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
// Check Connection to Database
if (mysql_connect($localhost, $username, $password))
{
#mysql_select_db($database) or die ("Unable to select database");
// Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
$query = "INSERT INTO $tablename VALUES ($yourdata)";
$result = mysql_query($query);
} else {
echo('Unable to connect to database.');
}
?>
And this is what I thought would work for 3 values but just doesn't end up working:
<?php
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
if ($key === "yourdata1"){
$yourdata1 = $value;
}
if ($key === "yourdata2){
$yourdata2 = $value;
}
// Check Connection to Database
if (mysql_connect($localhost, $username, $password))
{
#mysql_select_db($database) or die ("Unable to select database");
// Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
$query = "INSERT INTO $tablename(yourdata, yourdata1, yourdata2) VALUES ($yourdata, $yourdata1, $yourdata2)";
$result = mysql_query($query);
} else {
echo('Unable to connect to database.');
}
?>
I tried testing by entering the address in the URL like so
http://hydrosen.byethost11.com/insert_mysql1.php?yourdata=23&yourdata1=43&yourdata2=555
Like I said if I try it with one data value it works but it doesn't for three values. The table's column names are "yourdata" "yourdata1" and yourdata2".
Any help with this frustrating issue would be greatly appreciated
try this:
$yourdata = "";
$yourdata1 = "";
$yourdata2 = "";
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
if ($key === "yourdata1"){
$yourdata1 = $value;
}
if ($key === "yourdata2){
$yourdata2 = $value;
}
// Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
$query = "INSERT INTO $tablename('yourdata', 'yourdata1', 'yourdata2') VALUES ('$yourdata', '$yourdata1', '$yourdata2')";
Okay here goes. Connect.inc.php has credential info and functions .php just routes the data to another table I believe.I'm not sure if all this is necessary to post the data but my friend wrote all the additional code and we've been busy trying to get the rest of the project to work so I haven't gotten a full understanding of how this works yet.
<?php
//ob_start();
include_once 'functions.php';
include_once 'connect.inc.php';
$id =2; // Id of sensor
$yourdata = "";
$yourdata1 = "";
$yourdata2 = "";
foreach ($_REQUEST as $key => $value)
{
if ($key == "yourdata") {
$yourdata = $value;
}
if ($key === "yourdata1"){
$yourdata1 = $value;
}
if ($key === "yourdata2"){
$yourdata2 = $value;
}
$tot_data= $yourdata.','. $yourdata1.','.$yourdata2.';';}
//$tot_data= $yourdata.','. $yourdata1.','.$yourdata2.';';
if ($select_stmt = $connection->prepare("SELECT `sensor_id`, `wifidata` FROM `wifi` WHERE `sensor_id` = ? "))
{
//$id = $_SESSION['user_id'];
$select_stmt->bind_param('d', $id);
$select_stmt->execute(); // Execute the prepared query.
$res = $select_stmt->get_result();
if($res->num_rows==0)
{
if ($insert_stmt = $connection->prepare("INSERT INTO
`wifi`(`sensor_id`,`wifidata`)
VALUES(?,?) "))
{

Categories