null value when i opened the php script in IE - php

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 ?

Related

Change PHP mssql to sqlsrv (mssql_fetch_row)

I have this code:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
$encode = array();
//$query = strtr($query, array('{$raum}' => $raum));
$query_result = mssql_query($query);
while ($row = mssql_fetch_row($query_result))
{
$encode[] = $row;
$text = $row[1];
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row[0] . "</h2>" . $text . "<br>";
}
I have to change the connections to the sqlsrv model. I managed to do it this way:
$query="Select SUBJECT,NOTES from CAMPNOTIFICATION
where TYPE LIKE 'message_blackboard' AND VALIDAFTER <= GETDATE() AND (VALIDUNTIL >= GETDATE() OR VALIDUNTIL IS NULL)";
//$params = array(SQLSRV_PHPTYPE_*);
$encode = array();
$query_result = sqlsrv_query($connection, $query);
if ($query_result === false){
die(print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_object($query_result))
{
//echo "Contenido de Row ". $row -> NOTES;
$encode[] = $row;
$text = $row -> NOTES;
$text = str_replace("<br />","\n",$text);
$text = str_replace("<br>","\n",$text);
$text = str_replace("<br/>","\n",$text);
$text = str_replace("<p>","\n",$text);
$text = str_replace("\r","",$text);
$text = strip_tags($text);
$text = str_replace("\n","<br>",$text);
$text = str_replace("<br>\r<br>","",$text);
$text = str_replace("<br><br>","<br>",$text);
echo "<h2>" . $row -> SUBJECT . "</h2>" . $text . "<br>";
}
But I need to keep the structure in which I use the position of the array instead of calling the object.
Does anyone know of any way? Thank you very much.
Solution:
Function mssql_fetch_row() is part of the MSSQL PHP extension (mssql_ functions) and fetches one row of data as a numeric array. If you want to get the data in similar way using PHP Driver for SQL Server (sqlsrv_ functions), you should use sqlsrv_fetch_array() with SQLSRV_FETCH_NUMERIC as second parameter value.
Your code should look like this:
<?php
....
while ($row = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_NUMERIC)) {
$encode[] = $row;
// Additional code here ...
}
...
?>
Additional explanations:
If the SELECT statement returns more than one result set, you need to use sqlsrv_next_result() to make the next result of the specified statement active.
Example, using MSSQL extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$conn = mssql_connect($server, $username, $password);
mssql_select_db($database, $conn);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = mssql_query($sql, $conn);
// Fetch data
do {
while ($row = mssql_fetch_row($stmt)) {
echo print_r($row, true);
}
} while (mssql_next_result($stmt));
// End
mssql_free_result($stmt);
mssql_close($conn);
?>
Example, using SQLSRV extension:
<?php
// Connection
$server = "server\instance";
$database = "database";
$username = "username";
$password = "password";
$info = array(
"Database" => $database,
"UID" => $username,
"PWD" => $password
);
$conn = sqlsrv_connect($server, $info);
// Statement
$sql = "
SELECT [name], [age] FROM [dbo].[persons];
SELECT [name], [salary] FROM [dbo].[jobs];
";
$stmt = sqlsrv_query($conn, $sql);
// Fetch data
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo print_r($row, true);
}
} while (sqlsrv_next_result($stmt));
// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
Function equivalence:
The table below displays more information about the equivalence between the functions from each extension:
--------------------------------------------------------------------------------------
MSSQL PHP extension PHP Driver for SQL Server
--------------------------------------------------------------------------------------
mssql_fetch_assoc($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_row($stmt) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_ASSOC) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
mssql_fetch_array($stmt, MSSQL_NUM) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)
mssql_fetch_array($stmt, MSSQL_BOTH) sqlsrv_fetch_array($stmt, SQLSRV_FETCH_BOTH)
mssql_next_result($stmt) sqlsrv_next_result($stmt)

How do I store the results of the for loop as an array in the res variable?

I want to store the results of the for loop as an array in the variable
$res. How do I do it?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$sql1 = $con->query("SELECT (status) FROM `seita`");
$i = $sql1->num_rows;
echo $i;
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$res = mysqli_fetch_row($sql);
}
?>
The answer given by Rohit Mittal gave me array to string conversion error. What do I do next?
You can fetch all in one query with fetch_all() of mysqli
$servername = "localhost";
$username = "root";
$password = "";
$name = "abc";
$con = new mysqli ($servername, $username, $password, $name);
$result = $con->query("SELECT status FROM `seita`")->fetch_all();
You could try to do it all in one line. Maybe something similar to this:
$res = $con->query("SELECT status
FROM `seita`
WHERE RollNo between 1 and (
SELECT count(status)
FROM `seita`
)
")->fetch_all();
You want to append to an array search google php array append which gives array_push($stack, "apple", "raspberry");
// Declare arrray
$res = []
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
// Append result to array
array_push($res, mysqli_fetch_row($sql));
}
You need to make an array and need to get only status value as below:
$res = [];
for($x=1; $x<=$i; $x++)
{
echo $x;
$sql = $con->query("SELECT status FROM `seita` WHERE RollNo = '$x'");
$statusData = mysqli_fetch_row($sql);
$res[] = $statusData['status'];
}

Deprecated mysql_query and mysql_connect - code update

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.

Using preg_match on array from POST checkbox values

The problem I'm having is making preg_match work correctly for my array returned from my form.
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 1 (123)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 2 (456)">
<input type="checkbox" name="receiver-check[]" class="checkbox-id" value="Username 3 (789)">
So I wish to use preg_match on the values received through my form.
This is how I use it.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check']) ? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/\((\d+)\)$/', "$1", $receiver);
}
$number_of_receivers = count($receiverIds);
$while_count = 0;
while($number_of_receivers >= ($while_count + 1)){
$sql = <<< EOF
INSERT INTO private_messages (
message_subject,
message_content,
message_deliver,
message_receive,
message_status,
message_datetime,
message_to_stab
)VALUES
(?,?,?,?,'2',?,?);
EOF;
$stmt = $mysqli->prepare($sql) or die ("Feil i database<br>" . $sql . "<br><b>Feilmelding:</b> " . $mysqli->error);
$stmt->bind_param("ssiiii",$message_subject,$message_content, $_SESSION['user_id'],$receiverIds[$while_count],$message_datetime,$message_to_stab);
$stmt->execute() or die("noe gikk galt");
$msg_num_rows = $stmt->num_rows;
if($msg_num_rows = 0){
$msg = "Feilmelding: Klarte ikke å sende meldingen.";
}
else{
$msg = "Meldingen har blitt sendt.";
}
$stmt->free_result();
$stmt->close();
$while_count ++;
}
Then I use $msg_receiver_query to asign a value in the query INSIDE the while loop.
What I currently receive in my database is 0 and 1. Nothing else. What would the correct preg_match be for me to output JUST the numbers inside the paranthesis? and is there a more effective solution to this problem of mine?
It looks like you don't want to match, you want to extract just a portion of each $_POST['receiver-check'] value - so preg_replace() would be the right function to use.
$msg_receivers = !empty($_POST['receiver-check']) && is_array($_POST['receiver-check'])
? $_POST['receiver-check'] : array();
$receiverIds = array();
foreach($msg_receivers as $receiver) {
$receiverIds[] = preg_replace('/^.*\((\d+)\)$/', "$1", $reciever);
}
That should give you an array of reciever ids ($receiverIds) like:
array(
[0] => 123,
[1] => 456,
[2] => 789
);
You could do something like this.
This way you can insert it in to your DB. but you will query your Db 3 times to insert 3 records.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//Query, just change the table name and columns to what ever you need.
$sql = "INSERT INTO `table` (`column1`) VALUES ('" .$msg_receiver_query[0][0] . "')";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}
}else{
echo "nothing is set";
}
?>
Maybe a ittle to advanced but you can do this in one query aswell.
<?php
//use your connection Data
$user = "root";
$pass = "***";
$host = "localhost";
$dbdb = "TestDataBase";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
//check if receiver-check is set or not
if(isset($_POST['receiver-check'])){
$msg_receivers = $_POST['receiver-check'];
$inputArray = '';
// iterate through $msg_receivers
foreach($msg_receivers AS $value){
preg_match_all("/([0-9]{3})/", $value, $msg_receiver_query);
//insert all output in to an array
$inputArray [] = "('" . $msg_receiver_query[0][0] . "')";
}
//Insert all outputs in 1 query
$sql = "INSERT INTO `testtable` (`column1`) VALUES " . implode(",",$inputArray) . "";
if (mysqli_query($connect, $sql)) {
echo 'Record(s) created successfully<br>';
} else {
echo $sql . '"<br>"' . mysqli_error($connect);
}
}else{
echo "nothing is set";
}
?>

How to use rows of Mysql array in PHP function?

I have a function in PHP and I would like to export an array from my MYSQL Database and then use the rows in a loop to do some stuff with them.
$DB_Server = "XXX.XXX.XXX.XXX";
$DB_Username = "XXXX";
$DB_Password = "XXXXX";
$DB_Database = "XXXXX";
$conn = new mysqli($DB_Server, $DB_Username, $DB_Password, $DB_Database);
$query = "Select Name, Wert from test.DBPBX";
function show(array $options) {
global $showresult, $master, $conn, $query;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$cnlongname = $row["Name"];
$usercontent = $row["Wert"];
$cn = $cnlongname;
$options['config']->value = 1;
$config = $options["config"]->value;
$show = new SimpleXMLElement("<show/>");
$user = $show->addChild("user");
$user->addAttribute("cn", $cn);
if ($config)
$user->addAttribute("config", "true");
print "cmd: " . htmlspecialchars($show->asXML()) . "\n";
$showresult = $master->Admin($show->asXML());
print "result: " . htmlspecialchars($showresult) . "\n";
$mod = "text=".$usercontent;
$modify = new SimpleXMLElement("$showresult");
$user = $modify->user;
$path = explode("/device/hw/", $mod);
$srch = $user;
$nsegments = count($path);
$i = 1;
foreach ($path as $p) {
if ($i == $nsegments) {
// last part, the modification
list($attr, $value) = explode("=", $p);
$srch[$attr] = $value;
} else {
$srch = $srch->$p;
}
$i++;
}
$modify = new SimpleXMLElement("<modify>" . $user->asXML() . "</modify>");
print "cmd: " . htmlspecialchars($cmd = $modify->asXML()) . "\n";
// do it
$result = $master->Admin($cmd);
print "result: " . htmlspecialchars($result);
}
}
For $cn I would like to use $cnlongname (or $row["Name"]). And for $mod I would like to use $usercontent (or $row["Wert"]). However when I would like to use it I get an error after the first loop:
Warning: mysqli_fetch_assoc() expects parameter 1 to be
mysqli_result, string given in /sample.php on
line 175
Line 175 is:
while ($row = mysqli_fetch_assoc($result)) {
Can you please help me?
Inside your while loop you overwrite your result, therefore you lose your mysql result and cannot query it any more.
// do it
$result = $master->Admin($cmd);
Use a different variable there. :)

Categories