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(?,?) "))
{
Related
I´m trying to update my database with information that is send via a form.
My problem is that i don´t get how I can loop both arrays at the same. I have tried nesting foreach-loops with no success.
I then have this to work with
$display = $_POST["show"] ?? "";
$id = array_keys($_POST["show"]);
if ($action == "submit") {
foreach ($display as $key => $value) {
$stmt = $db->prepare("UPDATE picture SET display = ? WHERE id = ?");
$stmt->bindParam($display, $id)
$stmt->execute();
}
}
You can iterate over array and get keys and values at the same time:
$display = $_POST["show"] ?? [];
// Also you can check if `$display` is not empty
if ($action == "submit" && $display) {
// prepare statement ONCE
$stmt = $db->prepare("UPDATE picture SET display = ? WHERE id = ?");
foreach ($display as $key => $value) {
// execute statement as many times as you want with your params
$stmt->execute([$value, $key]);
}
}
If I saw correctly this is what you want:
<?php
try {
$display = isset($_POST['show']) ? $_POST['show'] : [];
if ($action === 'submit' && !empty($display)) {
$db->beginTransaction();
$stmt = $db->prepare('
UPDATE picture
SET display = :display
WHERE id = :id;
');
foreach ($display as $id => $show) {
$stmt->bindParam(':display', $show);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
}
$db->commit();
}
} catch(PDOException $e) {
echo $e->getMessage();
$db->rollBack();
}
<?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";
}
?>
Years ago a friend of mine wrote a piece of code for me to do some simple function of recording a learning progress for my joomla site users. Now that I have updated the Joomla to 3.6 on PHP7, the site is reporting deprecated queries which did not surprise me. I tried to replace the queries with mysqli but I have failed to make the function work. Would someone take a look for me? Thank you so much.
<?php
/* $host = "localhost";
$user = "administrator";
$pass = "web-Test";//enter here your sql password
$db_name = "e-learning";
$link = mysql_connect($host, $user,$pass);
mysql_select_db($db_name, $link)or die("unable to select database"); */
include'const.php';
$link = mysql_connect($host, $user,$pass);
if (!$link) {
echo('Could not connect');
}
else {
mysql_select_db($db, $link) or die("can not select database").mysql_error();
}
$ip=getenv('REMOTE_ADDR');
//$new_array_without_nulls = array_filter($_POST, 'strlen');
if($_POST)
{
// --------comment
$uid = $_POST['uid'];
unset($_POST['uid']);
$cmt = array();
foreach($_POST as $key => $value)
{
if ($value != 'true' && $value != 'Progress' && $value != 'false')
{
$cmt[$key] = $value;
}
}
foreach ($cmt as $key => $value)
$cmt_value = implode(',' , $cmt);
// --------Check
$check = array();
foreach($_POST as $key => $value)
{
if ($value == 'true')
{
$check[$key] = $value;
}
}
//finding key
$check_key = array();
foreach ($check as $key => $value){
array_push($check_key,$key);
}
foreach ($check_key as $key => $value)
$check_value = implode(',' , $check_key);
//$uid = $user->get('id');
$content_name = $_POST['contentname'];
function CheckExistContentName($content_name,$uid){
$name_exist = mysql_query("select * from Progress where content_name = '$content_name' and User_id = $uid ");
$arr = array();
while($row = mysql_fetch_array($name_exist))
{
$arr = $row;
}
return $arr;
}
if(CheckExistContentName($content_name,$uid))
{
$sql = "update Progress set User_id = '".$uid."', ip = '".$ip."',content_name = '".$content_name."',arr_check = '".$check_value."',arr_cmt = '".$cmt_value."' where content_name = '$content_name' and User_id = $uid";
$rs_result = mysql_query($sql);
echo "<h2> Your learning progress has been updated </h2>";
}
else
{
$sql = "insert into Progress(User_id,ip,content_name,arr_check,arr_cmt) values ('".$uid."','".$ip."','".$content_name."','".$check_value."','".$cmt_value."')";
$rs_result = mysql_query($sql);
echo "<h2> Your learning progress has been saved </h2>";
}
}
//}
?>
Your friend did it completely wrong in a Joomla sense. He hard coded a MySQL connection (including password) into a file instead of using the Joomla database class.
On top of that he is using unsafe variables directly in his MySQL queries, which means your site is at very high risk of being hacked.
If I was you, I would get a professional to fix this issue properly.
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);
}
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'; }