phpmyadmin: Connection failed: Unknown database. - database

I'm a beginner and a teacher trying to make a quiz and connect to the database. I'm using MAMP 7.0.6, also installed XAMPP on my window. I had a database called "students" on phpmyadmin and a script like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "students";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
It works fine when I tried to connect to the database without the $dbname, however, when I included that it says "Connection failed: Unknown database 'students'". I'm sure the name and username, password and stuff is correct, even though I don't know why the password has to be "" instead of the one shown on my phpmyadmin, but it works so I'll just leave it for later unless some of you would like to spend the time to explain it to me.
I just want to make this work asap coz it has been bugging me for a few days and I still can't find the solution online. I need to get the quiz done by mid August so thank you so much in advance!!!!

Related

Exporting SSRS Reports to PDF from Python

I am trying to export/print/generate SSRS reports from Python. It looks like SSPYRS should accomplish exactly what I am looking for. However, I get an error and can't find the ways around it.
import sspyrs
try:
username= "user"
password = "pass"
params_multi = {'param1': value1, 'param2': value2, 'param3': value3}
myrpt = sspyrs.report("http://sqlserver/reportingserrver/reportsfolder/reportname", username, password, params_multi).download('PDF',fileloc)
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
I get the following error:
Report Server does not allow usable data export methods. Update server settings/version to enable XML, Excel, or CSV export.
When I ran the the same reports from the browser everything is working fine. I can also access it without any problems from .net applications. So I doubt it's a permissions issues.
I checked reportserver.config file on SQL Server and PDF rendering is enabled. I am not sure where else I can look.
Any help guidance will be greatly appreciated.
So I had to use NTLM authentication to get it to work for me in my environment. Maybe you could use and/or modify this? I am SQL person, not python, but here goes:
import requests
from requests_ntlm import HttpNtlmAuth
#change username to your username
filename = 'C:\\Users\\username\\Desktop\\report.pdf'
#change username and password to your network login
username = "username"
password = "password"
#url needs to be the special url found by going to the ReportServer, the one with &rs:Command=Render
url = "http://reportservername/ReportServer%2fReportFolder%2fReportName&rs:Command=Render&rs:Format=PDF"
r = requests.get(url, auth=HttpNtlmAuth(username, password))
print(r.status_code)
if r.status_code == 200:
with open(filename, 'wb') as out:
for bits in r.iter_content():
out.write(bits)
This post helped me: https://www.reddit.com/r/Python/comments/67xak4/enterprise_intranet_authentication_and_ssrs/

Why is the Logins property null?

I'm trying to add a Windows user to an SQL Server. This works fine. However, if the user is already there, I don't want to get an error. If it's already there, that's fine. So I thought I would just check before creating it:
$AccountName = $args[0]
$ComputerName = $args[1]
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$sqlSrv = New-Object 'Microsoft.SqlServer.Management.Smo.Server' ($ComputerName)
$sqlSrv.Refresh() # TRIED DIFFERENT THINGS HERE, REFRESH, INITIALIZE...
$login = $sqlSvr.Logins[$AccountName] # HERE .Logins IS NULL
if ($login -eq $null) {
$login = New-Object 'Microsoft.SqlServer.Management.Smo.Login' ($sqlSrv, $AccountName)
$login.Name = $AccountName
$login.LoginType = 'WindowsUser'
$login.PasswordPolicyEnforced = $false
$login.Create()
}
I don't know why the Logins Property of the SQL Server class is null. I can see the existing logins in SQL Management Studio.
Can anybody tell me how to properly check if a login exists before creating it? With Roles and Databases, the Server's properties seem to be filled.
I'm using Sql Server Express Version 11.0.5058.0 (I think that's 2012) and Powershell Version is 5.0.10586.117.
Change this to this $sqlSvr.Logins to $sqlSrv.Logins
$sqlSvr.Logins to $sqlSrv.Logins

Changing Active Directory user password with PHP script

I am trying to get a very simple PHP script to change a user password in my Active Directory domain.
Here is the script I found some where online:
<?php
$uid = 'Mohammed Noureldin';
$newPassword = '5omeGoodP#ssword';
$bindDn = 'CN=Administrator,OU=UsersOU,DC=example,DC=local';
$bindPassword = 'An0therGoodP#ssword';
$baseDn = 'OU=UsersOU,DC=example,DC=local';
$protocolVersion = 3;
$ldap = ldap_connect('localhost');
if (!ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, $protocolVersion))
{
exit('Failed to set protocol version to '.$protocolVersion);
}
// bind anonymously so that we can verify if the server really is running
ldap_bind($ldap);
if (ldap_errno($ldap) !== 0)
{
exit('Could not connect to LDAP server');
}
// now bind with the correct username and password
ldap_bind($ldap, $bindDn, $bindPassword);
if (ldap_errno($ldap) !== 0)
{
exit('ERROR: '.ldap_error($ldap));
}
$searchResults = ldap_search($ldap, $baseDn, 'cn='.$uid);
// no matching records
if ($searchResults === false)
{
exit('No user found');
}
if (!is_resource($searchResults))
{
exit('Error in search results.');
}
// create the unicode password
$len = strlen($newPassword);
$newPass = '"';
for ($i = 0; $i < $len; $i++)
{
$newPass .= "{$newPassword{$i}}\000";
}
$newPass .= '"';
$entry = ldap_first_entry($ldap, $searchResults);
if (!is_resource($entry))
{
exit('Couldn\'t get entry');
}
$userDn = ldap_get_dn($ldap, $entry);
if (!$userDn)
{
exit('Errrrrrrrrr1');
}
if (!ldap_modify($ldap, $userDn, array('unicodePwd' => $newPass)))
{
exit(ldap_errno($ldap)." ". ldap_error($ldap));
}
?>
The output of this PHP page was this error message:
53 Server is unwilling to perform
And the script simply didn't work (the password of the user was NOT changed).
I know the main principle that AD stores the passwords in unicodePwd field (if that is still the case till now), and I knew that I have to use secure connection and I am using it (hopfully it is correctly setup).
I googled about that error message but I couldn't find any functional solution.
I also tried some other scripts but this one was the best till now because the others gave me some errors in some previous steps (for example binding).
I really appreciate any help to solve that problem, or even another functional script may be a good idea!
Thanks in advance.
You may not change a password using this method unless you connect over SSL/TLS. If you Google or Bing for the word unicodePwd, which you already knew because you included it in your post, one of the first if not the first result will be the MSDN documentation for unicodePwd, which states within the first three sentences:
This attribute is written by an LDAP Modify under the following
restricted conditions. Windows 2000 operating system servers require
that the client have a 128-bit (or better) SSL/TLS-encrypted
connection to the DC in order to modify this attribute. On Windows
Server 2003 operating system, Windows Server 2008 operating system,
Windows Server 2008 R2 operating system, Windows Server 2012 operating
system, Windows Server 2012 R2 operating system, and Windows Server
2016 Technical Preview operating system, the DC also permits
modification of the unicodePwd attribute on a connection protected by
128-bit (or better) Simple Authentication and Security Layer
(SASL)-layer encryption instead of SSL/TLS. In Windows Server 2008,
Windows Server 2008 R2, Windows Server 2012, Windows Server 2012 R2,
and Windows Server 2016 Technical Preview, if the
fAllowPasswordOperationsOverNonSecureConnection heuristic of the
dSHeuristics attribute (section 6.1.1.2.4.1.2) is true and Active
Directory is operating as AD LDS, then the DC permits modification of
the unicodePwd attribute over a connection that is neither
SSL/TLS-encrypted nor SASL-encrypted. The unicodePwd attribute is
never returned by an LDAP search.
If you just perform a simple search for unicodePwd, again one of the very first
results you'll get is STEP BY STEP CODE on how to do this:
https://support.microsoft.com/en-us/kb/269190
Realise I'm a year late to this party; but having discovered this post whilst troubleshooting a similar problem...
Suspect ldaps is/was providing a certificate that wasn't trusted by the server hosting this php script (linux?); OP mentions having changed the code to use ldaps and getting to exit('Could not connect to LDAP server'); but connecting OK via Apache Directory Studio which may be on a machine that DOES trust the certificate (ie a domain joined workstation that trusts the DC).
To fix this proper, investigate your Private Key Infrastructure (a big topic, start here : https://social.technet.microsoft.com/wiki/contents/articles/2980.ldap-over-ssl-ldaps-certificate.aspx)
Alternatively, just tell the php server to trust the LDAP self-signed cert as see: Authenticating a self-signed certificate for LDAPS connection
To verify this is the case before embarking (ie not recommended in production) consider configuring LDAP on the php host (assumed linux server) to ignore errors caused by the certificate authority/trust by doing putting
TLS_REQCERT never
at the end of /etc/ldap/ldap.conf
(restart apache / webserver after change)
As Ryan Ries has noted, you must make a secure connection in order to change a password, but the code you've posted does not do so.
The problematic code is:
$ldap = ldap_connect('localhost');
As you can see, this makes a non-secure connection.
To make a secure connection, you need to specify an LDAPS URI:
$ldap = ldap_connect('ldaps://localhost');
You're creating the unicode password wrong. Here is code that works at least for me on Server 2012.
// create the unicode password
$newpassword = "\"" . $newpassword . "\"";
$len = strlen($newpassword);
for ($i = 0; $i < $len; $i++) $newpass .= "{$newpassword{$i}}\000";
$entry["unicodePwd"] = $newpass;
// Modify the password
if (ldap_mod_replace($ldap, $userDn, $entry))
{
exit("Successfully updated password!");
}
Notice how I encode the " with the new password, that was the trick that got it working for me.
$server = "ldaps://172.1.200.1:636";
$dn = "dc=srv,dc=world";
$message = array();
function changePassword($server,$dn,$user,$oldPassword,$newPassword,$newPasswordCnf){
global $message;
error_reporting(0);
putenv('LDAPTLS_REQCERT=allow');
$con=ldap_connect($server);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
$findWhat = array ("cn","mail");
$findWhat = array();
$findWhere = $dn;
$findFilter = "(sAMAccountName=$user)";
$ldaprdn = 'mydomain' . "\\" . $user;
$ldapbind = ldap_bind($con, $ldaprdn, $oldPassword);
if ($ldapbind) {
$message[] = "ldapbind ($ldapbind) with sAMAccountName=$user";
} else {
$error = ldap_error($con);
$errno = ldap_errno($con);
$message[] = "ldapbind error $errno - $error";
ldap_close($con);
return false;
}
$sr = ldap_search($con,$dn,$findFilter,$findWhat);
$records = ldap_get_entries($con, $sr);
if ($records["count"] != "1") {
$message[] = "Error E100 - Wrong user or password.";
return false;
}else {
$message[] = "Found user <b>".$records[0]["cn"][0]." DN=".$records[0]["dn"]." </b>". print_r($records[0],true);
}
$entry = array();
#seems a more correct way that handles complicated characters
$entry["unicodePwd"] = iconv("UTF-8", "UTF-16LE", '"' . $newPassword . '"');
# base64_encode is only needed in ldif text files !
#$entry["unicodePwd"] = base64_encode($newPassw);
$result = ldap_modify($con,$records[0]["dn"],$entry);
if ($result === false){
$message[] = $newpass.",".$entry["unicodePwd"]." Your password was not changed . with:".print_r($result, true);
$error = ldap_error($con);
$errno = ldap_errno($con);
$message[] = "$errno - $error";
}
else {
$message[] = " Your password has been changed. ";
//mail($records[0]["mail"][0],"Password change notice : ".$user,"Your password has just been changed.");
}
ldap_close($con);
}
I'm running SAMBA 4.11 as AD/DC and had to use ldap_modify_batch to get this working.
$modifs = [
[
"attrib" => "unicodePwd",
"modtype" => LDAP_MODIFY_BATCH_REMOVE,
"values" => [iconv("UTF-8", "UTF-16LE", '"' . $curPassword . '"')],
],
[
"attrib" => "unicodePwd",
"modtype" => LDAP_MODIFY_BATCH_ADD,
"values" => [iconv("UTF-8", "UTF-16LE", '"' . $newPassword . '"')],
],
];
$result = ldap_modify_batch($ldapconn, $dn, $modifs);
error_log("Batch modify result:".print_r($result, true));
$errorMessage = ldap_errno($ldapconn)." ". ldap_error($ldapconn);
error_log("$errorMessage:".$errorMessage);

How to upload database using Dropbox?

I've just created a Barcode Scanner app and have a database of barcode. I want to upload/sync this database to the company's server then another programmer can get and build website UI. Unfortunately, our server is not public (but it can connect internet through proxy), so I want to use Dropbox to do that. Could you please give me a useful sample code or tell me the best way to upload/sync database in this case? I am extremely grateful for your help!
Alright, assuming your database is a MySQL DB with a host environment that lets you run cron jobs, access your FTP, etc... here's a possible code snippet for you, I just had to do this myself with the Dropbox API, you can actually read the full post here for a walk-thru (Dropbox API and MySQL DB Dump/Upload
<?php
# Include the Dropbox SDK libraries
require_once __DIR__."/dropbox-sdk/lib/Dropbox/autoload.php";
use \Dropbox as dbx;
//your access token from the Dropbox App Panel
$accessToken = 'NOT-A-REAL-TOKEN-REPLACE-THIS-QM8jS0z1w1t-REPLACE-THIS-TOKEN';
//run the MySQL dump and zip;
// location of your temp directory
$tmpDir = "your_temp_dir";
// username for MySQL
$user = "DB_user";
// password for MySQL
$password = "DB_password";
// database name to backup
$dbName = "DB_name";
// hostname or IP where database resides
$dbHost = "your_hostname";
// the zip file will have this prefix
$prefix = "sql_db_";
// Create the database backup file
$sqlFile = $tmpDir.$prefix.date('Y_m_d_h:i:s').".sql";
$backupFilename = $prefix.date('Y_m_d_h:i:s').".tgz";
$backupFile = $tmpDir.$backupFilename;
$createBackup = "mysqldump -h ".$dbHost." -u ".$user." --password='".$password."' ".$dbName." --> ".$sqlFile;
//echo $createBackup;
$createZip = "tar cvzf $backupFile $sqlFile";
//echo $createZip;
exec($createBackup);
exec($createZip);
//now run the DBox app info and set the client; we are naming the app folder SQL_Backup but CHANGE THAT TO YOUR ACTUAL APP FOLDER NAME;
$appInfo = dbx\AppInfo::loadFromJsonFile(__DIR__."/config.json");
$dbxClient = new dbx\Client($accessToken, "SQL_Backup");
//now the main handling of the zipped file upload;
//this message will send in a system e-mail from your cron job (assuming you set up cron to email you);
echo("Uploading $backupFilename to Dropbox\n");
//this is the actual Dropbox upload method;
$f = fopen($backupFile, "rb");
$result = $dbxClient->uploadFile('/SQL_Backup/'.$backupFilename, dbx\WriteMode::force(), $f);
fclose($f);
// Delete the temporary files
unlink($sqlFile);
unlink($backupFile);
?>
You also need to make a config.json file like so:
{
"key": "YOUR_KEY_FROM_DROPBOX_APP_PANEL",
"secret": "YOUR_SECRET_FROM_DROPBOX_APP_PANEL"
}
You will need to create a new Dropbox app under your Dropbox account to get your key and secret, and to generate the auth code for your username, do that here when logged in: https://www.dropbox.com/developers/apps
You also need to download the Dropbox PHP SDK library to put on your server in the same folder as this PHP code above, find that here: https://www.dropbox.com/developers/core/sdks/php
Hope this helps; if you need more step-by-step or your developer does, go that link at the top for a full walk through.

Drupal Password set

I have to reset my password direct through database for that I used query
UPDATE users SET pass = md5('NEWPASSWORD') WHERE name = 'admin'
but still I am not able to login.
Can you please tell me where I am going wrong?
With drupal 7, password are no more encrypted through md5.
There are several way to reset a password in drupal7.
Using drush :
drush upwd admin --password="newpassword"
Without drush, if you have a cli access to the server :
cd <drupal root directory>
php scripts/password-hash.sh 'myPassword'
Now copy the resultant hash and paste it into the query:
update users set name='admin', pass='pasted_big_hash_from_above' where uid=1;
If you are working on a remote environment on which you cannot connect, you can put this specified code in a file such as password.php such as this one:
<?php
if (isset($_GET['p'])) {
require_once dirname(__FILE__) . '/includes/bootstrap.inc';
require_once dirname(__FILE__) . '/includes/password.inc';
print _password_crypt('sha512', $_GET['p'], _password_generate_salt(DRUPAL_HASH_COUNT));
exit();
}
print "No password to hash.";
And then hit your site using: http://domain.tld/password.php?p=MyPassword. The hash will appear on your browser's tab.
Don't forget to remove it once you done it.
Are you locked out of your account? If you've got DB access then try clearing out the "flood" table.

Resources