php mongo Uncaught exception 'MongoDuplicateKeyException' E11000 - php

I am trying to migrate data from mysql to mongo. It adds one record fine to mongo but then on the second record I am getting
Fatal error: Uncaught exception 'MongoDuplicateKeyException' with message 'localhost:27017: E11000 duplicate key error index: app.hospitals.$_id_ dup key: { : ObjectId('558365d7423467484bd63af3') }'
Not sure what I am doing wrong
here is my code
<?php
//echo phpinfo();
$host = "localhost";
$user = "root";
$password = "root";
$database = "database";
// Create connection
$conn = new mysqli($host, $user, $password, $database);
$connection = new MongoClient();
$db = $connection->database;
$collection = $db->hospitals;
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM hospitals";
if($result = $conn->query($sql)){
$i=0;
while($row = $result->fetch_assoc()) {
foreach($row as $key=>$value){
$collection->insert($row);
unset($collection->_id);
}
if($i > 3) die;
$i++;
}
}
$conn->close();
?>

using
$collection->save($row);
instead of insert solved the issue. Not sure why though.

Had the same problem, I believe it's a problem with the PHP mongodb driver that it is not generating a new id inside the loop.
The weird part that the first time I called the script it inserted all the documents then the exception popped in the end, then when I dropped the database and called the script again, it only inserted one document before giving the exception.
Anyway I solved after reading this answer by explicitly assigning new id.
In your case, add this before the insert:
$row['_id'] = new MongoId();

Related

Migrating from xamp to raspberry pi apache server

I'm currently working on a project. It's almost done, there's only one big problem. I tested my code all the time with a xamp server on my computer, which worked perfectly fine. the goal is to run it (apache server, mysql database) on my raspberry pi. Now my project is finished, I came figured out the problem why my code doesn't work on my raspberry (at least not as I expected).
I turned on error reporting in PHP and came to this error message:
Notice: Trying to get property of non-object in /var/www/html/test.php on line 41
I use this function for all my SQL queries. Can someone provide a solution so I don't have to rewrite the whole code? Thanks in advance!
PS: this is just a piece of the code (the function where I pull the data out of the database + example of one of my queries)
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****"; // I just dont want to give my sql database password its nothing wrong ;)
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
print_r("ok connection");
function sqlquery ($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //line 41 in my code ==> do a while loop to fetch all data to an array
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
}
$stateLoop = "1";
}
else { // if there are no results
}
}
$sql1 = "SELECT stopTijd FROM gespeeldeTijd WHERE naam = 'thomas' ORDER BY ID DESC LIMIT 1"; // get data with SQL query
sqlquery($sql1,$conn,"stopTijd");
if ( $stateLoop == "1") {
print_r("ok loop");
$date1 = $myArray["0"];
print_r($date1);
$myArray = [];
$stateLoop == "0";
}
}
?>
It pretty much looks like you have some sql error in your query; check if your field names in your database match those on the raspberry.
Seeing through your code it seems like you are pretty new to programming (which is no bad thing, I was once, too). So I made a few more modifications to your code showing you the prettiness of PHP
use "return" in function sqlquery instead of globals
check for errors after executing the code
use only one variable to check if data was loaded
I commented everything I changed
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "test";
// Your function with some modifications
function sqlquery($sql, $conn, $naamtabel) {
$result = $conn->query($sql);
// Check for errors after execution
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
// If we have no data, we simply return an empty array
if($result->num_rows == 0)
return array();
// This is a variable we store the data we processed in
// We will return it at the end of our function
$myArray = null;
// Read all field data and store it $myArray
while($row = $result->fetch_assoc())
$myArray[] = $row[$naamtabel]; // if you use "$naamtabel" here, PHP first needs to interpret the string (= slower)
return $myArray;
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Because we use "die" above we don't need an "else"-clause
print_r("ok connection");
$sql = "SELECT `stopTijd` FROM `gespeeldeTijd` WHERE `naam` = 'thomas' ORDER BY `ID` DESC LIMIT 1";
$data = sqlquery($sql, $conn, "stopTijd");
// $data will contain $myArray (see "return $myArray" in function sqlquery)
// Instead checking for $stateLoop being "1" we check if $data contains any values
// If so, we fetched some data
if(sizeof($data) >= 1) {
print_r("ok loop");
$date1 = $data[0]; // No "0", because we are trying to get index 0
print_r($date1);
$data = array(); // Are you sure this is nessecary?
} else {
echo 'No data returned from query!';
}
?>
Note: code tipped on my smartphone -> untested!
If you don't want to adapt the code I wrote, the important part for this question is:
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
Your error Notice: Trying to get property of non-object means "you are trying to get num_rows from $result, but $result is not an object, so it can't contain this property".
So to figure out why $result is not an object, you need to get the error from $conn->query - my code above probably won't fix your error, but it will display you one you can work with (+ it's too long for a comment)
If you have a more detailed error message and you can't solve it on your own, feel free to comment; I will update my answer!

Call MySQL stored procedure from PHP

I have looked at several examples on how to call a MySQL stored procedure from PHP but none have helped me. The stored procedure works when run inside PHPMyAdmin but I am having trouble calling it from the web.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
header('refresh:1; url=schedule_main_scores.php');
else
echo "failed";
?>
There's 2 problems here.
You're querying twice and using the wrong variable, being $sql instead of $result.
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
^^^^^^^^^^^^ calling the query twice
^^^^ wrong variable, undefined
all that needs to be done is this:
if ($result)
and an else to handle the (possible) errors.
Error reporting and mysqli_error($conn) would have been your true friends.
http://php.net/manual/en/function.error-reporting.php
http://php.net/mysqli_error
Side note: You really should use proper bracing techniques though, such as:
if ($result){
echo "Success";
}
else {
echo "The query failed because of: " . mysqli_error($conn);
}
It helps during coding also and with an editor for pair matching.

Deletion of row in MySQL using php

I have been developing a CRUD application using PHP & MySQL database.
I was succeeded by creating, displaying, updation parts. But I stuck at the deletion part of a row from a database table.
I tried my best solving all the PHP shown errors but now in final it is now showing a message which I wrote to echo in case of failure.
I request someone to please help me with this problem.
Thankyou in advance.
Code I wrote for deletion:
//include database connection
include 'db_connect.php';
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "DELETE
FROM `grocery`
WHERE `GrocerID` ='".$mysqli->real_escape_string($_GET['id'])."'
limit 0,1";
//execute query
if( $mysqli->query($query) ){
//if successful deletion
echo "User was deleted.";
}else{
//if there's a database problem
echo "Database Error: Unable to delete record.";
}
$mysqli->close();
?>
Code I wrote for delete link in display table:
//just preparing the delete link to delete the record
echo "<a href='delete.php?id={$GrocerID}'>Delete</a>";
Code I wrote for db config:
<?php
//set connection variables
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
?>
I tried this and got working, can you update the code and see if this works?
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
// Delete row
if ($mysqli->query (sprintf( "DELETE FROM grocery WHERE email = '".$mysqli->real_escape_string($_GET['id'])."' LIMIT 1") )) {
printf ( "Affected Rows %d rows.\n", $mysqli->affected_rows );
}
I hope this helps.
Provide a connection :
if( $mysqli->query($con, $query) ){

PHP getting data from SQL from database

Hey I'm wanting to retrieve some data from the a database. But it seems whenever I enter my credentials into the SQL database to retrieve the data I get the following error:
Since i presume this is a similar use case as your last question
Your php file is missing the configuration of the connection:
<?php
$dbuser = "******";
$dbpass = "*******";
$db = "SSID";
$connect = OCILogon($dbuser, $dbpass, $db);
if (!$connect) {
echo "An error occurred connecting to the database";
exit;
}
So it knows which connection you are using and passing to the checkUserPass() function.
UPDATE:
For the table name you need to pass $dbtable as you can see in the function declaration
function checkUserPass($connect,$username, $password, $dbtable)
so either set a $dbtable variable before calling the function:
$dbtable="register_table";
or send it immediately as a string:
function checkUserPass($connect,$username, $password, "register_table")

Cloud SQL using mysqli error

I'm trying to output the results of a simple query using a Google Cloud SQL with a mysqli connection. I've properly set up a Cloud SQL instance and imported a SQL database. However, when I run my app, it seems to connect to the database - no errors are triggered there - but the logs show the following:
PHP Fatal error: Wrong SQL: SELECT * FROM students Error: No database selected in /base/data/home/apps/s~db-php-001/1.371796924944999585/main.php on line 18
Here's my code:
$conn = new mysqli(null,"root","",null,null,"/cloudsql/db-php-001:db-instance-001");
// check connection
if($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$sql='SELECT * FROM students';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $rs->num_rows;
}
Obviously, I'm triggering that error, but I'm can't figure out why. There is definitely a table named students in the database.
Anyone have any ideas?
Thanks!! Joe
You've set your database name to null. A connection is made like so:
$mysqli = new mysqli("localhost", "user", "password", "database");
The mysqli constructor can take in the following parameters (in this order):
$mysqli = mysqli($hostname, $username, $password, $database, $port, $socket);
In your case, you've set the parameters to be:
$hostname = null; //Defaults to mysqli.default_host
$username = "root";
$password = "";
$database = null; //Defaults to ""
$port = null; //Defaults to mysqli.default_port
$socket = "/cloudsql/db-php-001:db-instance-001";
To clarify, you can pass null for the database name. In the query you'd need to use the fully qualified table name (<database>.Students in your case). Or you can use the mysqli_select_db() function to select the database to use.

Categories