PHP - Php Mongodb Driver Connection And Insert
Hello guys, I've installed the mongoDB PHP driver using "sudo pecl install mongodb" Testing shows driver is installed correctly and it appears nicely in phpinfo(): ludo@aegir:~$ php7.2 -i | grep -i mongodb mongodb MongoDB support => enabled MongoDB extension version => 1.5.3 MongoDB extension stability => stable mongodb.debug => no value => no value For connecting I've got: $db = new MongoDB\Driver\Manager("mongodb://localhost:27017"); Now I want to define a collection and insert a record, i've been using code from here https://www.php.net/manual/en/set.mongodb.php: $collection = $db->mydatabase->mytable; $result = $collection->insertOne( [ 'name' => 'test', 'item' => 'testitem' ] ); But this fails Notice: Undefined property: MongoDB\Driver\Manager::$mydatabase in /var/www.... Has anyone got a workingg example of defining and inserting into mongoDB. Seems the driver was updated fairly recently and so stuff on the internet is not always relevant. Edited May 17, 2019 by ludo1960Similar Tutorialsis this a server problem its the first time ive come across it. does this mean theres a problem with the PDO driver on the Mysql server.??????? is there a way of solving this the notebook lenovo g 780 runs windows 8 and is not very stable. the WLAN connecgtion is not very stable _ despite the fact that it is very very close to the router . btw: several linux-notebooks (opensuse) which are running under the same condition do not have any problem want to load a new driver - but which one is corrcet? how to find out which driver is needed? http://www.lenovo-dr...rivers-download Networking: LAN (Ethernet) Atheros LAN Driver Windows 8 (32-bit) Windows 8 (64-bit) 3.17MB Download Networking: LAN (Ethernet) Atheros Lan Driver Windows XP 3.02MB Download Networking: LAN (Ethernet) Atheros LAN Driver Windows 7 (32-bit) Windows 7 (64-bit) 5.33MB Download Networking: Wireless LAN Intel WiMax Driver Windows XP 64MB Download Networking: Wireless LAN Wireless LAN Driver (Liteon, CyberTan) Windows 8 (32-bit) Windows 8 (64-bit) 49.4MB Download Networking: Wireless LAN Intel WLAN Driver Windows XP 203MB Download Networking: Wireless LAN Intel WiMax Driver Windows 8 (32-bit) Windows 8 (64-bit) 88.7MB Download Networking: Wireless LAN WLAN Driver (Liteon, Cybertan) Windows XP 41.8MB Download Networking: Wireless LAN Intel Wireless LAN Driver Windows 8 (32-bit) Windows 8 (64-bit) 540KB Download how to find out which driver is needed? Hi, I hope you guys can help me out. I only know basic PHP and also SQL. I haven't tried using connecting database yet. My problem is that I'm trying to INSERT a data into an existing table using access but when it reaches $rs = odbc_exec(); it returns an error that the query was empty. Here is the code: Code: [Select] $conn=odbc_connect('trial','',''); if (!$conn) {exit("Connection Failed: " . $conn);} $sql = "INSERT INTO Data (FirstName, LastName, BusinessName) VALUES ('$fname', '$lname', '$bname')"; $rs=odbc_exec($sql, $conn); $rs = @odbc_exec($conn,$sqlstring); if (!$rs) { echo "An error has occured. Please try again", odbc_errormsg($conn); } else { echo "The record was successfully inserted."; } odbc_close($conn); and here is the error: Quote An error has occured. Please try again[MySQL][ODBC 5.1 Driver][mysqld-5.5.20]Query was empty I really hope you could help me out. Thanks. Hi, Ive stumbled apon a Mongo database connected to a broadcast script. I would like to change it to a Mysql database can anybody please show me an example how it will look in Mysql format
<?php /* Require the PHP wrapper for the Mxit API */ require_once ('MxitAPI.php'); /* Function to count the number of users in MongoDB */ function count_users() { $mongo = new Mongo('127.0.0.1'); $collection = $mongo->sampleapp->users; $collection->ensureIndex(array('uid' => 1)); return $collection->count(); } /* Function to get batches of users from MongoDB */ function get_users($skip=0, $limit=50) { $mongo = new Mongo('127.0.0.1'); $collection = $mongo->sampleapp->users; $collection->ensureIndex(array('mxitid' => 1, 'created_at' => 1)); $users = $collection->find()->sort(array('created_at' => 1))->skip($skip)->limit($limit); return iterator_to_array($users); } /* Instantiate the Mxit API */ $api = new MxitAPI($key, $secret); /* Set up the message */ $message = "(\*) Congratulations to our winners (\*)\n\n"; $message .= "1st place - Michael with 100 points\n"; $message .= "2nd place - Sipho with 50 points\n"; $message .= "3nd place - Carla with 25 points\n\n"; $message .= 'Good Luck! :) $Click here$'; /* Mxit Markup is included in the message, so set ContainsMarkup to true */ $contains_markup = 'true'; /* Count the number of users in the database */ $count = count_users(); /* Initialise the variable that counts how many messages have been sent */ $sent = 0; /* Keep looping through the user list, until the number of messages sent equals the number of users */ while ($sent < $count) { /* Get users in batches of 50 */ $users = get_users($sent, 50); /* The list where the user MxitIDs will be stored */ $list = array(); foreach ($users as $user) { $list[] = $user['mxitid']; $sent++; } /* If there is a problem getting an access token, retry */ $access_token = NULL; while (is_null($access_token)) { /* We are sending a message so request access to the message/send scope */ $api->get_app_token('message/send'); $token = $api->get_token(); $access_token = $token['access_token']; // Only attempt to send a message if we have a valid auth token if (!is_null($access_token)) { $users = implode(',', $list); echo "\n$sent: $users\n"; $api->send_message($app, $users, $message, $contains_markup); } } } echo "\n\nBroadcast to $sent users\n\n"; Hi all, this is driving me crazy - I must be doing something obviously wrong. I want to load the Microsoft PHP PDO drivers. I have checked my phpinfo and found the following:- PHP Version 5.3.8 Loaded Configuration File C:\Program Files (x86)\PHP\php.ini extension_dir C:\Program Files (x86)\PHP\ext So I put the file 'php_pdo_sqlsrv_53_ts_vc9.dll' in the extension dir. I then added the following line the correct php.ini file:- ;;;;;;;;;;;;;;;;;;;;;; ; Dynamic Extensions ; ;;;;;;;;;;;;;;;;;;;;;; extension=php_pdo_sqlsrv_53_ts_vc9.dll But when I check php info the sqlsrv driver does not appear to be loaded, not even after a reboot. All I see is: PDO drivers mysql, odbc, sqlite Not sure what I have missed. How can I tell if PHP has tried to load the sqlsrv drivers? Thanks Kev This topic has been moved to PHP Installation & Configuration. http://www.phpfreaks.com/forums/index.php?topic=350565.0 This topic has been moved to Installation in Windows. http://www.phpfreaks.com/forums/index.php?topic=347714.0 Can anyone tell me why this is not INSERTing? My array data is coming out just fine.. I've tried everything I can think of and cannot get anything to insert.. Ahhhh! <?php $query = "SELECT RegionID, City FROM geo_cities WHERE RegionID='135'"; $results = mysqli_query($cxn, $query); $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($row = mysqli_fetch_array($results)) { $insert_city_query = "INSERT INTO all_illinois SET state_id=$row[RegionID], city_name=$row[City] WHERE id = null" or mysqli_error(); $insert = mysqli_query($cxn, $insert_city_query); if (!$insert) { echo "INSERT is NOT working!"; exit(); } echo $row['City'] . "<br />"; echo "<pre>"; echo print_r($row); echo "</pre>"; } //while ($rows = mysqli_fetch_array($results)) } //if (mysqli_num_rows($results)) else { echo "No results to get!"; } ?> Here is my all_illinois INSERT table structu CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; Here is my source table geo_cities structu CREATE TABLE IF NOT EXISTS `1` ( `CityId` varchar(255) NOT NULL, `CountryID` varchar(255) NOT NULL, `RegionID` varchar(255) NOT NULL, `City` varchar(255) NOT NULL, `Latitude` varchar(255) NOT NULL, `Longitude` varchar(255) NOT NULL, `TimeZone` varchar(255) NOT NULL, `DmaId` varchar(255) NOT NULL, `Code` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; I'm missing something here. I have a form, and when the submit is pressed, the relevant post data inserts into table one, then I want the last insert id to insert along with other form data into a second table. The first table's still inserting fine, but I can't get that second one to do anything. It leapfrogs over the query and doesn't give an error. EDIT: I forgot to add an error: I get: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage, why VALUES ('14', '', '123', '','1234', '', '')' at line 1 query:INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('test 14', 'asdfa', 'asdf', 'adf','asdf', '', '', '', '123', '', '') Code: [Select] if (empty($errors)) { require_once ('dbconnectionfile.php'); $query = "INSERT INTO tbl_donar (donar_fname, donar_name, donar_address, donar_address2, donar_city, donar_state, donar_zip, donar_email, donar_phone, donar_fax, donar_company) VALUES ('$description12', '$sn', '$description4', '$cne','$description5', '$description6', '$description7', '$description8', '$description9', '$description10', '$description11')"; $result = @mysql_query ($query); if ($result) { $who_donated=mysql_insert_id(); $query2 = "INSERT INTO tbl_donation (donor_id, donor_expyear, donor_cvv, donor_cardtype, donor_authorization, amount, usage, why) VALUES ('$who_donated', '$donate2', '$donate3', '$donate4','$donate5', '$donate6', '$donate7')"; $result2 = @mysql_query ($query2); if ($result2) {echo "Info was added to both tables! yay!";} echo "table one filled. Table two was not."; echo $who_donated; //header ("Location: http://www.twigzy.com/add_plant.php?var1=$plant_id"); exit(); } else { echo 'system error. No donation added'; Hi! I got the following problem... I have a SQL 2005 Server in a VPN. For security reasons,internet access to the database server is only possible for VPN members. Now i want to connect to the openvpn Server from my webserver in order to connect to the database for some webreports. How can i achieve this using php? thanks Hi Guys, need a little help and drawn a blank. The code that is not working is below $result = $conn->query("SELECT * FROM MK_migration_details WHERE mig_bid='".$_SESSION['bid']."'"); I can confirm the $_SESSION['bid'] is working as echo's out on another part of the page. and the above $result works when i manually type the search criteria like below. $result = $conn->query("SELECT * FROM MK_migration_details WHERE mig_bid='300101'"); Basically no result turn up on the page. Any ideas or advise how I can diagnose? Fatal error: Call to undefined function mysql_connect() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\connect\index.php on line 10 Hallo I am beginner and starting to learn php I got this message when I want to connect with server. Can I get some suggestion what to do? Thanks HI fellow programmers, Can i connect a textbox to a field in the MySql using the id of the text box? If yes, can u show me a small example. Thanks RAM Hi All, I have a landing page that I use, but often my sql database is too busy or gets overwhelmed and then the landing page just stalls and traffic is lost. Here it is: Code: [Select] <?php //ini_set("display_errors",1); if(!$src) $src = $q; define("__EXEC_", 1); include("config.php"); include("custom.php"); function lsp_visit_find($__val, &$__uid) { global $u; global $db; $l_campaign = array("campaign_id"=>"", "url"=>"", "cost"=>"0.00", "name"=>"-", "ad_keyword"=>"", "mapped_keyword"=>""); $l_visit = array(); $q = $_GET['q']; $src = $_GET['src']; // for STAGE #1 (visit definition): get cost, ad keyword, mapped keyword. $l_campaign['name'] = "info"; $l_campaign['mapped_keyword'] = "$q"; $l_campaign['ad_keyword'] = "$src"; $l_campaign['cost'] = ".02"; // get referer (campaign URL). if no campaign found, - create it! if (!empty($l_campaign['name'])) { $r = mysql_query("select campaign_id,name from campaign where name='$l_campaign[name]'"); if (!mysql_affected_rows($db)) { $r = mysql_query("insert into campaign(name,cost, creation_date,last_update_date) values('$l_campaign[name]',$l_campaign[cost], unix_timestamp(),unix_timestamp())"); $l_campaign['campaign_id'] = mysql_insert_id($db); } else { $w = mysql_fetch_assoc($r); $l_campaign = array_merge($l_campaign,$w); } } // check, whether we had visits from this IP for this keywords within 2 minutes. // if we have one, get its ID, otherwise - create new! $visit_id=""; if (!empty($l_campaign['ad_keyword']) && !empty($l_campaign['mapped_keyword']) ) { $ip = get_real_ip(); $r = mysql_query("select visit_id,uid,campaign_id,ad_keyword,mapped_keyword from visit where ip='$ip' and ad_keyword='$l_campaign[ad_keyword]' and mapped_keyword='$l_campaign[mapped_keyword]' and currtime>=from_unixtime(".(time()-120).") limit 1"); if (!mysql_affected_rows()) { $__uid = md5($ip.time().$l_campaign['campaign_id']); $x = mysql_query("insert into visit(ip,uid,cost,currtime,campaign_id,ad_keyword,mapped_keyword) values('$ip','$__uid',$l_campaign[cost],now(),$l_campaign[campaign_id],'$l_campaign[ad_keyword]','$l_campaign[mapped_keyword]')"); $visit_id = mysql_insert_id($db); } else { $l_visit = mysql_fetch_assoc($r); $visit_id = $l_visit['visit_id']; $__uid = $l_visit['uid']; } return $visit_id; } } $db = mysql_connect(__CFG_HOSTNAME, __CFG_USERNAME, __CFG_PASSWORD); mysql_select_db(__CFG_DATABASE, $db); $u = isset($_GET['u'])? $_GET['u'] : 2; $uid = ""; $visit_id = lsp_visit_find($_REQUEST['l'], $uid); if (!empty($visit_id)) { setcookie("x_uid", base64_encode($visit_id."QQ".$uid), time() + 3600); } global $q; mysql_close($db); $q = $_GET['q']; $src = $_GET['src']; header("Location: http://www.mydomain.com/search/?q=$q"); exit(); ?> My question is how do I code it so that if after 5 seconds or so, or the connection can't be made, it just terminates the connection and auto loads the header redirect at the bottom of the page? Thanks! <?php class UserQuery { public function Adduser($id,$username,$email,$password) { $conn = new Config(); $sql =("INSERT INTO test.user (id, username, email, password) VALUES ('$id', '$username', '$email',$password)"); $conn->exec($sql); } }
getting an "exec doesnt exist " error, saying exec doesnt exist in my db file. it doesnt need to exist does it ? anyone any idea why ?
Hello, Does anyone know how may i detect the Connection type by user IP? Broadband etc. I have an app that connects to a source safe server to perform a command via shell_exec(). I had used exec(), but shell_exec seems to work better since I am on Linux. The command connects to the server and tells it to promote a file to the next level. On Windows this ran without a hitch, but on Linux I gat an error that reads: Quote Socket error when reading request from [172.20.22.1]: 3537808 ; Socket closed. I am told that the reason for this error is that PHP broke the connection to the server before the server completed the job and was able to shutdown properly. The only way I have found around this is to place a sleep(3) to the script. This is really not ideal since that means that there is at least 3 seconds between each command, which can really extend the time it takes to perform if there are numerous files. If PHP breaks the connection before the program can close it will leave the program open and PHP cannot perform any more commands to the server since it is stuck on the last command. If too many are given the machine will lock up due to resources being eaten up. I'm wanting to know if there is a way to tell PHP to not let go of a connection so quickly. I tried "nohup", but that does not help. I am new to Linux and am at a loss of what my options are beyond the sleep() method. I really feel that there has to be a better way or setting that can be manipulated to fix this issue altogether. Thanks in advance for any help. Cy Hi, I'm trying to write my first MVC framework for my college project and faced this problem: i have main framework class, and have this loader class, that loads view files and libraries. Now, how can I do that when I load library, I could reach it from my main class? For example: in main class goes this code: Code: [Select] public $load; function __construct ( ) { $this->load = new Loader; } function someFunction ( ) { $this->load->library('someLibrary'); // and now reach the library like this $this->someLibrary->functionInLibrary(); } The idea is from codeigniter, so if anyone has used this framework will understand my question. Hi I have been following a youtube tutorial trying to update my php knowledge and they use pdo to create the DB wrapper class and once i load my index.php through WAMP server i get the following on screen error: QuoteSQLSTATE[HY000] [1049] Unknown database 'lr' THIS IS THE DB CLASS FILE,
<?php
THIS IS THE INIT.PHP FILE
<?php
$GLOBALS['config'] = array (
spl_autoload_register(function ($class) { require_once 'functions/sanitize.php';
and this is the index.php file
<?php $user = DB::getInstance()->query("SELECT username FROM users WHERE username = ?", array('alex'));
if(!$user->count()) {
Edited January 17, 2020 by Michael_Baxter Hi,
I'm trying to write a better PHP code to create and manage my website.
I would like to start a MVC approach with PHP, using OOP. So I can manage the updates in a better way. For example, to begin my project, I would try with the shipping cost of our products, using a Class without merge the PHP and HTML code.
Something like this:
$shippingcost=new ShippingCost(); $shippingcost->state="Italy"; $shippingcost->get(); // here I have an array with cost, discount, time ecc.And If I need it in JSON, I write: $shippingcost->get("JSON"); // here I have the JSON with cost, discount, time ecc.I wrote the Class in this way: class ShippingCost { public $state; private $arrayReturned; public function __construct() { $this->stato="Italy"; // the default state } public function __destruct() { } public function get($format="array") { $this->arrayReturned=array( "cost" => 3.99, "costDiscounted" => 7.99, "discount" => "50%" ); if (strtolower($formato)=="json") { $this->arrayReturned=json_encode($this->arrayReturned); } return $this->arrayReturned; } }It works well, but I need to get the values from a MySQL db. How can pass the MySQL connection to the Class? I'm not able to do this. Thanks in advance and have a great 2015. Rob. |