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.
Related
I am trying to fetch the values from mysql table based on the certain values. below is my php script where i am getting json values from android and then parse it to array the passing array in to the select query.
So, when i open the script in IE i am getting values as null instead of []. What is wrong here.
php
<?php
$username = "xxxxx";
$password = "xxxxxx";
$host = "localhost";
$database="xxxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$JSON_received = $_POST["JSON"];
$obj = json_decode($JSON_received,true);
foreach ($obj['ilist'] as $key => $value)
{
//echo "<br>------" . $key . " => " . $value;
$im[] = $value;
}
$myquery = "SELECT * FROM Movies WHERE im_rat IN ('$im')";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
Can anyone help ?
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(?,?) "))
{
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'; }
So I've been working on a little automatic payment system, and I'm almost done! My customers will get their account upgraded automatically after payment, but I have a slight problem.
I'm currently manually adding their username to an array which changes their username style to distinguish their rank.
I would like to know how to make it retrieve and successful go into an array which will then be called and show their new username.
Here is my code for retrieving usernames and then putting into an array:
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT * FROM members")or die(mysqli_error());
$names = array();
while($listnames = $listmembers->fetch_assoc()) {
$names[] = "'" . $listnames['username'];
}
$newname = explode("\", ", $names);
Okay and this is what my array code looks like
$members = array($newname);
And this is the code changing their rank:
if(in_array(strtolower($rows['received']), $members)) {
$user = "" . ucfirst($rows['received']) . "";
}
If anyone cold help me, i'd appreciate it.
Turn warnings on to see a few of your mistakes..
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT * FROM members")or die(mysqli_error());
$names = array();
while($listnames = $listmembers->fetch_assoc()) {
$names[] = $listnames['username'];
}
and later something like this..
if(in_array(strtolower($rows['received']), $names)) {
$user = "<font color=\"lime\"><b>" . ucfirst($rows['received']) . "</b></font>";
}
why you don't fetch array directly from database?
$db = new mysqli("localhost", "changed", "changed", "changed")or die(mysqli_error());
$listmembers = $db->query("SELECT username FROM members")or die(mysqli_error());
$names = $listmembers->fetch_all();
and then:
foreach ( $names as $username ) {
if ( strtolower($rows['received']) == $username[0] ) {
$user = ucfirst($rows['received']);
break;
}
}
Script searchs through DB and fix broken links. Search and replace functionality works fine, but when trying to save updated data scripts wrights only first raw. I'm stucked! I can use simple mysql_query commands to update data, but needs PDO...
header('Content-Type: text/html; charset=UTF-8');
error_reporting(E_ALL);
echo "Welcome";
$mysql = new PDO('mysql:host=localhost;dbname=db_name;charset=UTF-8','user','12345');
if (!$mysql) die('Can\'t connect');
$tables = array(
'categories',
'news',
'pages'
);
function getContent($table) {
global $mysql;
$fieldnum = 0;
$fields = array();
$vals = array();
$st = $mysql->query("SHOW FIELDS FROM `{$table}`");
while ($row = $st->fetch(PDO::FETCH_ASSOC)) {
$fields[$fieldnum]=$row["Field"];
$fieldnum++;
}
$totalfields=$fieldnum;
$res = $mysql->query("SELECT * FROM `{$table}`");
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
while ($row = $res->fetch(PDO::FETCH_NUM)) {
for ($j=0; $j<$res->columnCount();$j++) {
$rs = str_replace('index.php/','',$row[$j],$m);
if ($rs && $m>0) {
if ($table == 'categories')
$prim= 'cat_id';
elseif($table == 'news') $prim= 'news_id';
elseif($table == 'pages') $prim= 'page_id';
else $prim= $table.'_id';
$upd = $mysql->prepare($sql);
$update = $upd->execute(array(
':table'=>$table,
':field'=>$fields[$j],
':val'=>$rs,
':idf'=>$prim,
':id'=>$row[0]
));
}
}
}
}
foreach ($tables as $t) {
getContent($t);
}
Need help to fix it!
try to fetch all and then go through array
and you do not need to use prepare every time - just once see Example #2
....
$res = $mysql->query("SELECT * FROM `{$table}`");
$rows = $res->fetchAll(PDO::FETCH_NUM);
$sql = "UPDATE `:table` SET :field = ':val' WHERE `:idf` = :id;";
$upd = $mysql->prepare($sql);
foreach ($rows as $row) {
foreach ($row as $col_name => $value) {
......
prepare outside the loop! you are loosing its value this way, also try $upd->debugDumpParams(); and binding before execution, maybe the values u r binding is not right.