Mongodb select collection is not working in php - php

I am trying to get the data from the mongo db table (location) for this i am
trying to use selectCollection() function of mongo db but it is giving following error i am new on mongo db that why i am not getting why this error
occured.
object(MongoCollection)#3 (2) { ["w"]=> int(1) ["wtimeout"]=> int(10000) }
Below is my php code
<?php
$host = "xxxx";
$user = "xxxx";
$pass = "xxx";
$db = "xxxx";
$port = "xxxx";
$con = new MongoClient("mongodb://{$host}:{$port}");
$data = $con->selectDB($db);
if ($user != '' && $pass != '')
$record=$data->authenticate($user, $pass);
$location = $data->selectCollection('location');
var_dump($location);die;
?>
Please help me thanks in Advance.

Related

php/mysql connection on different servers

I have a local and a remote server on which I am developing a project
//local
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";
//remote
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";
At the moment I am commenting out the //local or //remote bit depending which way I am connecting. Of course, I regularly overwrite the connection file by mistake which is a pain.
Is there some sort of way I can detect which server I am on, and then connect automatically. I have tried googling but couldn't turn anything up maybe because i couldn't think of the right search terms.
Thanks
You can try this code:-
<?php
if ($_SERVER['SERVER_NAME'] == "localhost") {
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";
}
elseif ($_SERVER['SERVER_NAME'] == "google.com") {
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";
}
else {
echo "No configuration found!";
exit;
}
There are more than a few ways of doing this but one you could try is to detect which server you are on from the IP Address
if ($_SERVER['SERVER_ADDR'] === '127.0.0.1') {
$servername = "localhost";
$username = "bob";
$password = "fred";
$dbname = "jane";
} else {
//remote
$servername = "arthur";
$username = "Milly";
$password = "Horace";
$dbname = "Erastus";
}
try this code :-
$conn = new mysqli($servername1, $username1, $password1);
if (! $conn->connect_error) {
$conn = new mysqli($servername2, $username2, $password2);
}
Or check :-
$_SERVER['HTTP_HOST']=="localhost"

PHP Insert Query Using Prepare Statement

I have created an insert form. I'm doing an insertion operation into MySQL using prepare statement but it's not working. I don't understand what's wrong. Please help me to solve this issue. Is this what I did correct?
insert.php
<?php
include('dbconn.php');
session_start();
$_SESSION['example']='Session Created';
$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
$sql = "Insert into main(client,category,sd,fd) values(:client,:category,:sd,:fd)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':client',$_POST['client'],PDO::PARAM_STR);
$stmt->bindParam(':category',$_POST['category'],PDO::PARAM_STR);
$stmt->bindParam(':sd',$_POST['sd'],PDO::PARAM_STR);
$stmt->bindParam(':fd',$_POST['fd'],PDO::PARAM_STR);
$stmt->execute();
?>
dbconn.php
<?php
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$mysqli = new mysqli($host,$user,$pwd,$db);
/* ESTABLISH CONNECTION */
if (mysqli_connect_errno()) {
echo "Failed to connect to mysql : " . mysqli_connect_error();
exit();
}
?>
Its always good to put up the errors you are having.
You are using two different database connection types pdo, and mysqli. You only need one.
I stripped your code down to the minimum.
<?php
$host = "localhost";
$user = "root";
$pwd = "root";
$db = "eservice";
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
//$srn = $_POST['srn'];
$client = $_POST['client']; // required
$category = $_POST['category'];
$sd = $_POST['sd']; // required
$fd = $_POST['fd'];
// make sure client and sd are set here
$stmt = $pdo->prepare("
INSERT INTO
main
(client,category,sd,fd)
VALUES
(:client,:category,:sd,:fd)
");
$success = $stmt->execute([
'client' => $client,
'category' => $category,
'sd' => $sd,
'fd' => $fd
]);

PHP mysqli->prepare returning nothing

I'm trying to use a mysqli connection to retrieve rows from my database however I continue to receive a 500 internal server error no matter what I try.
$getUserQuery = "SELECT * FROM members WHERE name = ? AND member_id > 0";
$getUserStatement = $mysqli_conn->prepare($getUserQuery);
$getUserStatement->bind_param("s", $name);
$mysqli_conn->ping() results in a value of true so I know there's no issue with the database connection. var_dump($getUserStatement) results in bool(false) so there's some issue with the prepare. Whole code:
$user_dirty = $_GET['u'];
$pass_dirty = $_GET['p'];
$getUserQuery = "SELECT * FROM members WHERE name = ? AND member_id > 0";
$getUserStatement = $mysqli_conn->prepare($getUserQuery);
if ($getUserStatement) {
echo($getUserStatement);
} else {
echo("not good");
}
$getUserStatement->bind_param("s", $user_dirty);
$getUserStatement->execute();
$getUserResult = $getUserStatement->get_result();
And how I create my DB connection:
$mysql_host = "host";
$mysql_user = "user";
$mysql_password = "pass";
$mysql_database = "db";
$mysqli_conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
You gets 500 internal error because statement is false probably(https://stackoverflow.com/a/845025/2962442 turn on display errors), not resource like it should be, it can be caused by lost connection, try ping or reconnect before prepare.
Example good code:
$getUserQuery = "SELECT * FROM members WHERE name = ? AND member_id > 0";
$getUserStatement = $mysqli_conn->prepare($getUserQuery);
if ($getUserStatement) {
$getUserStatement->bind_param("s", $name);
} else {
//statement is false, not good
}
and good example of connection part
$mysql_host = "host";
$mysql_user = "user";
$mysql_password = "pass";
$mysql_database = "db";
$mysqli_conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if (!$mysqli_conn) {
//not connected...
}

New $_SESSION variable not created after query?

I'm trying to build a login process where, by using $_SESSION variables, the login credentials of the user are stored and used to show their relevant data from the database on screen (i.e. they will only see the school data that they work for).
<?php
session_start();
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{
$host = "xxx";
$username = "xxx";
$password = "xxx";
$database_name = "xxx";
$table_name = "xxx";
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
$query = "SELECT Class FROM $table_name WHERE Initials = '".
$_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
$result = mysql_query($query);
$class = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count === NULL)
{
echo "ERROR";
}
else
{
$_SESSION['Class'] = $result;
echo "Class added to sessions";
}
}
?>
My initial problem where the query couldn't recognize the session variables was easily solved by adding the correct brackets for the if-statement. My next problem that has arisen here is that even though the query should be successfull (I don't receive an error message saying 'ERROR' when the $count is either FALSE or NULL) it's not creating the result array into a new session, because when I print the session array on a new page it's still only carrying over the 'Initials' and 'Surname' sessions.
What do I need to change to my query, or post-query process in order for that array (because it's bound to throw up multiple results) to be made into a new session?
Many thanks for the answers to my initial problem!
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}
u need { } brackets
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
$host = "xxxxx"; $username = "xxxxx"; $password = "xxxxx";
is
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";
I've found the answer - it turned out that I wasn't treating one of the session variables as a proper array and thus wouldn't load properly. I've added my script below so that people with similar problems in the future can use it as a reference point:
<?php
session_start();
// Server Details //
$host = "---";
$username = "---";
$password = "---";
$database_name = "---";
$table_name = "---";
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
// Query to call up the unique school name //
$query_school = mysql_query("SELECT DISTINCT School FROM $table_name
WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_school = mysql_result($query_school, 0);
// Query to call up the unique centre no //
$query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM
$table_name WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_centreno = mysql_result($query_centreno, 0);
// The newly created sessions for school info //
$_SESSION['---'] = $result_school;
$_SESSION['---'] = $result_centreno;
// Query to call up the array of classes //
$query_class = mysql_query("SELECT Class FROM $table_name WHERE
Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$query_class__array = array();
while($row = mysql_fetch_assoc($query_class))
$query_class_array[] = $row;
$_SESSION['---'] = $query_class_array;
?>

Returning Query Result

So, I'm writing this application in PHP where the user has a "Student's Name" and each user has a unique student name. So, before I go any further with my problem, here is the code
*Note I've already prevented the SQL injections
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3) or die("Can not connect to Server.");
$query3 = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
$student1name = "$query3";
return $student1name;
So, the person enters the username which the registered before hand and each user has a student name.I start a query which selects student1 and student1 is equal to student1name. Student 1 name is then defnied as query3. When I test it all out, all I get is (null).. Does anyone know the problem? Thank you!
I suspect what you want is something like this:
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3) or die("Can not connect to Server.");
$query3 = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
while ($row = mysqli_fetch_array($query3))
{
$student1name = $row['student1'];
}
return $student1name;
This will put the contents of the last returned row of your query, column "student1", into the variable $student1name, and return it.
You are not fetching data from result. Try this:
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3)
if (!$con3)
throw new Exception("Connection error");
$result = mysqli_query($con3,"SELECT student1 FROM users WHERE username = '$username123'");
if ($result)
return $result->fetch_object();
else
throw new Exception("Query error: " . mysqli_error($con3));
}

Categories