Passing variable in php as a parameter to mongodb remove() function - php

I want to remove a document in mongodb-php. I am accepting an id from the user and using that I want to delete the document but it gives me an error
"Deprecated: MongoCollection::remove(): Passing scalar values for the
options parameter is deprecated and will be removed in the near future
in C:\wamp\www..process.php on line 12".
here is my code
<?php
$m = new mongo();
echo "Connection to database successfully";
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycollection;
echo "Collection selected succsessfully";
$collection->remove(array("Team_ID"=>$_POST['team_id']),false);
echo "Documents deleted successfully";
$cursor = $collection->find();
// iterate cursor to display team_id of documents
echo "Updated document";
foreach ($cursor as $document) {
echo $document["Team_ID"] . "\n";
}
?>

As the error states, it doesn't accept scalar values as a second parameter. Instead, use an array with options (http://php.net/manual/en/mongocollection.remove.php).
$collection->remove(array('Team_ID' => $_POST['team_id']), array('justOne' => false));
As "justOne" is false by default, you can omit the second parameter.
$collection->remove(array('Team_ID' => $_POST['team_id']));

Related

How to insert text from php to a mongo database

I'm looking to insert the text input provided by user on a webpage in a text input field(comment box) I created using php, to a mongo database, how do I do that?
First of all you have to connect with Mongo Database then create collection and then insert the desire value in json format.
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycol;
echo "Collection selected succsessfully";
$inputTextValue= array(
"key" => "value",
);
$collection->insert($inputTextValue);
echo "inputTextValue inserted successfully";
?>
Try this hope this code useful for you
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycol;
echo "Collection selected succsessfully";
$document = array(
"field_name" => "Your text input field "
);
$collection->insert($document);
echo "Document inserted successfully";
?>

Want to fetch data from database based on dropdown list selection using php [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below.
Here is my php file;
<?php
$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$sql="SELECT id,planname,price FROM plan";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=planname value=''>Plan Name</option>"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[planname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
if(isset($_REQUEST['planname'])){
// connection should be on this page
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
$res = mysql_fetch_assoc($sql);
echo $res['price'];die;
}
echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';
?>
I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
You are searching in the column planname, but by defining the <option>'s as
echo "<option value=$row[id]>$row[planname]</option>";
You are sending the id as value.
So your query should be:
$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));
Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?
The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.
How to do implement your plan
You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)
1. The frontend:
As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).
To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.
So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.
Note:
I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp
I think you should check out jQuery if you haven't yet, it makes things really really easy.
Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.
I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>
2. The backend: (in this case called ajax.php)
A simple piece of code, nothing special to do.
First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.
Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.
Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.
Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}
$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}

Load mysql data to Highcharts line chart using JSON

I'm trying to import my data from a database to a line chart (Highcharts). My code doesn't work.
Here is my PHP code:
<?php
require('../php/config.php');
$con=mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['src']))
{
$records=array();
$records = select($mysqli,"SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while($r = mysql_fetch_assoc($records)) {
$rows['data'][]=$r['data'];
}
return json_encode($rows);
}
else
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
?>
It seems that "mysql_fetch_assoc" doesn't work. The output of my array $rows id that:
{
"name": "Totale"
}
There isn't an element called "data".
What am I doing wrong?
At first:
It would be worth to see what is in your ../php/config.php file, because the content of that file may impact the behavior of other lines you provided.
The structure and data (at least few lines of data) of occupazione table is also worth to see, because data or structure could change the output as well.
You are missing a { after the else, - as #Moppo already mentioned.
Warning on mysql_fetch_assoc
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Read more in php.net
After that and some more fixes I would finally write your code in the way close to that:
<?php
$con = mysqli_connect("localhost", "root", "ginnastica", "progetto");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_GET['src'])) {
$records = $con->query("SELECT Sesso AS name, Occupati AS data FROM occupazione WHERE Sesso='totale' AND Periodo LIKE '%2008'");
$rows = array();
$rows['name'] = 'Totale';
while ($r = $records->fetch_assoc()) {
$rows['data'][] = $r['data'];
}
return json_encode($rows, JSON_NUMERIC_CHECK);
} else {
return json_encode(array('status' => 'error', 'details' => 'no src provided'));
}
As I said, we know nothing about database you work with, so my guess would be that your select returns no lines as a result. And then you got no data (only {"name": "Totale"}), just because while has nothing to iterate throw.

Results not being returned for MongoDB query in PHP

I am not getting any results returned from the database when accessing the PHP file directly, however all the echo checks below are returning expected results.
This is entire PHP file.
<?php
$ext = new ReflectionExtension('mongo'); // see http://php.net/manual/en/reflectionextension.getversion.php
var_dump($ext->getVersion()); // returns string(5) "1.3.4"
echo extension_loaded("mongo") ? "loaded<br />" : "not loaded<br />"; // check if driver installed - returns "loaded"
$dbhost = '127.x.xx.x';
$dbname = 'mydb';
$m = new Mongo("mongodb://$dbhost"); // also tried 'MongoClient' rather than 'Mongo'
if ($m == true) {
echo "<br />connected to {$m}<br />"; // returns "connected to 127.x.xx.x:27017
}
$db = $m->$dbname;
$collection = $db->myCollection;
echo "<br />my collection is called {$collection}<br />"; // returns "my collection is called mydb.myCollection"
$query = $collection->find();
if ($query == true) {
echo "<br />the find method works"; // this is being returned
}
foreach($query as $result) { // nothing is happening here
var_dump($result);
}
?>
Command line query for:
db.myCollection.find();
is returning expected results (there is one document).
What version of PECL mongo lib are you using? if >= 1.3.0 (we are now on 1.4.3 stable), the Mongo class is deprecated and you are encouraged to use MongoClient instead.
Please refer to phpDoc.
Solution
Adjust above code to:
$dbhost = 'username:password#127.x.xx.x:27017/';
$dbname = 'yourdbname';
$m = new MongoClient("mongodb://$dbhost");
In my case I needed to define IP address.

"Array" Appearing Before JSON Ouput

I'm new to PHP and I don't understand why there is an extra word ARRAY infront of the JSON string.
Heres the output of JSON String:
Array{"Users":[{"UserID":"1","FirstName":"lalawee","Email":"12345","Password":null},{"UserID":"2","FirstName":"shadowblade721","Email":"12345","Password":null},{"UserID":"3","FirstName":"dingdang","Email":"12345","Password":null},{"UserID":"4","FirstName":"solidsnake0328","Email":"12345","Password":null}],"success":1}
This is the PHP file:
<?php
/*
* Following code will list all the Users
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all Users from Users table
$result = mysql_query("SELECT * FROM Users") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// Users node
$response["Users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$user[] = array();
$user["UserID"] = $row["UserID"];
$user["FirstName"] = $row["FirstName"];
$user["Email"] = $row["Email"];
$user["Password"] = $row["Password"];
// push single User into final response array
array_push($response["Users"], $user);
}
// success
$response["success"] = 1;
echo $response;
// echoing JSON response
echo json_encode($response);
}
else {
// no Users found
$response["success"] = 0;
$response["message"] = "No Users found";
// echo no users JSON
echo json_encode($response);
}
?>
Remove
echo $response;
which is printing the word Array. If you try to echo the array, it will display the word 'Array' rather than printing the content of an array itself. Use print_r() function to display the content of an array.
print_r($response);
With the exception of classes that use the __to_string magic method, echo and print will only output the string interpretation of a variable's value. Number types (integers and floats), strings, and (I think) booleans have a straightforward string representation. Any other variable (arrays, objects, resources) will either output nothing, their variable type, or throw a fatal error.
For arrays and objects, print_r() will go through each member/property and attempt to convert it to a string (print_r being shorthand for print_recursive). So print_r($response) will give you the full array.
Bear in mind that generally the full array is only useful to output for debugging. Passing a php string version of an array to javascript is likely to be useless.

Categories