PHP cannot connect to MySQL - php

I am reading the head first book on PHP and MySQL. Just started chapter 2 where they connect to database. But my script doesn't do anything. I get no error from the "or die" even when I purposefully enter the incorrect connection string, and the query doesn't insert. I am running Ubuntu server 14 with PHP 5.6.4 and MySQL 5.6.24 on a VM on my Mac.
I can connect remotely with MySQL workbench and execute the query which is successful.
Here is the my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Aliens Abducted Me - Report an abduction</title>
</head>
<body>
<h2>Aliens Abducted Me - Report an abduction</h2>
<?php
$name = $_POST['firstname'] . ' ' . $_POST['lastname'];
$when_it_happened = $_POST['whenithappened'];
$how_long = $_POST['howlong'];
$how_many = $_POST['howmany'];
$alien_description = $_POST['aliendescription'];
$what_they_did = $_POST['whattheydid'];
$fang_spotted = $_POST['fangspotted'];
$email = $_POST['email'];
$other = $_POST['other'];
echo 'Thanks for submitting the form ' . $name . '<br />';
echo 'You were abducted ' . $when_it_happened;
echo ' and were gone for ' . $how_long . '<br />';
echo 'You saw ' . $how_many . ' of them' . '<br />';
echo 'Describe them: ' . $alien_description . '<br />';
echo 'What the did: ' . $what_they_did . '<br />';
echo 'Was Fang there? ' . $fang_spotted . '<br />';
echo 'Your email address is ' . $email . '<br />';
echo 'Additional information: ' . $other;
$dbc = mysqli_connect('127.0.0.1', 'root', 'password', 'aliendatabase')
or die('Error connecting to server');
$query = "INSERT INTO aliens_abduction (first_name, last_name, " .
"when_it_happened, how_long, how_many, alien_description, " .
"what_they_did, fang_spotted, other, email)" .
"VALUES ('Sally', 'Jones', '3 days ago', '1 day', 'four', " .
"'green with 6 tenticles', 'We talked and played with a dog', " .
"'yes', 'I may have seen your dog', 'sally#gregs-list.net')";
$result = mysqli_query($dbc, $query)
or die ('Error querying DB');
mysqli_close($dbc);
?>
</body>
</html>
I have tried changing the host to localhost, ip address, loopback address all with and without the port number. But what the most frustrating thing is that I get no errors. Even when I should be.
I have even read up on different ways to create the connect/error commands using "if" i.e.
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
no difference. What is going wrong?

try this one
$dbc = mysqli_connect("localhost","root","password",'aliendatabase');
if(!$dbc)
{
echo "cannot connet to the server";
}
$q = "Your insert query here";
$query=mysqli_query($dbc, $q)
or die("Error: ".mysqli_error($dbc));
mysqli_close($dbc);

Thanks for getting back to me, i appreciate it. I discovered what the issue is. The errors not displaying was thanks to the errors not being setup in my php.ini (display_errors=off, needs to be changed to on). then i got this error "Fatal error: Call to undefined function mysqli_connect()" and this was because mysqli extension was not installed. Can be checked with php -m | grep on linux, if returns nothing then mysqli is not installed. install php5-mysqlnd and restart apache. Then fixed thanks for all the help.

Related

how to change mysql database code into postgresql code using core php?

I am using function based database connection and select query also plz help me.
FIRST CODE:
function connectDb(){
//my postgresql db connection
$link=pg_pconnect('host=' . __DB_HOST__ . ' port=' . __DB_PORT__ . ' dbname=' . __DB_NAME__ . ' user=' . __DB_USER__ . ' password=' . __DB_PWD__) or die('connection failed');
AllDelete();// Audit Logs Auto Deletion
}
SECOND CODE:
function AllDelete(){
$MysqlForLogs=pg_query("select audit.*,users.username from audit,users where audit.user_id=users.id and DATE_PART('day',now()-audit.date) > 7") or die(pg_last_error());
$CountRows=pg_num_rows($MysqlForLogs);
}
I am executing the browser it will show on error like 'No database selected' but really i am giving the database name.
What is the problem?

XML Parsing Error: junk after document element. Google maps database interaction

Hi so I'm trying to pull data from a database to be used with Google Maps following the advice from a Google developers article: https://developers.google.com/maps/articles/phpsqlajax_v3. I have copied their exact code in an attempt to just get a start before manipulating it but it keeps throwing the following error: XML Parsing Error:
junk after document element
Location: http://localhost/Google/phpsqlajax_xml3.php
Line Number 2, Column 1:
^
I know the same error has been posted before, but I'm yet to find a solution that works for me. Any advice is appreciated! Here's my code, straight from google:
<?php
//require("phpsqlajax_dbinfo.php");
$username="root";
$password="";
$database="my_db";
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect('localhost', $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
Just in case anyone else is stuck with a similar issue it was resolved by changing all the mysql statements to their mysqli equivalent.

PHP block after html not executing

I have two blocks of code in the body section of an html ( .php) document. The code block before my heading executes, but the block after the heading does not. I've tried phpinfo(); in the first block and it runs fine. Try it in the second block and it doesn't. I have no idea why this could be. If anyone has suggestions I'm all ears.
I'm currently running xampp on a windows machine.
<body>
<?php
if (isset($_SESSION['ProfileID'])){
echo "<div style='text-align: right'>"
. "<a href='CZSN_Login.php'>Log "
. "Out</a></div>\n";
}
//here phpinfo() executes
?>
<h1>Chinese Zodiac Social Network</h1>
<?php
require_once("Includes/inc_ChineseZodiacDB.php");
//here phpinfo() will not execute
if (isset($_SESSION['ProfileID'])){
echo "<h2>Member Pages</h2>\n";
echo"<p>Below is a list of the members of the Chinese Zodiac Social"
. "Network. Click on a member's name to view that member's detailed information"
. "You may also choose to <a href='CZSN_MyProfile.php'>update your profile</a>.</p>\n";
$SQLQuery="select first_name, last_name, user_name "
. "from zodiac_profiles order by "
. "last_name, first name, user_name;";
$result=$DBConnect->query($SQLQuery);
if ($result===false){
echo $ErrorMsgs[];
}
else{
//This should never happen, but we can check anyway.
if ($result->num_rows==0){
echo "<p>There are no members to show.</p>\n";
}
Here is the code in my inc_ChineseZodiacDB.php file:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
Try searching in require_once ("Includes / inc_ChineseZodiacDB.php"); there can be triggered die() or exit();
I guess you get "Error headers already sent", because of the title <h1>Chinese Zodiac Social Network</h1>. For phpinfo() to work there shouldn't be any output yet.
You are closing the php tag in the inc_ChineseZodiacDB file (i.e. you have ?> at the end of that file).
When your first file reads in the inc_ChineseZodiacDB file and sees the ?>, it interprets that as the end of your php section of code, and all the other code after require_once("Includes/inc_ChineseZodiacDB.php"); is ignored and read as regular html.
Remove that line, and your problem should be fixed:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
I figured out the ultimate problem. in the include file it reads:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
where it should read:
<?php
$ErrorMsgs = array();
$DBConnect = #new mysqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
Note, I was calling msqli rather than mysqli. One simple typo...I'm still not understanding why the error messages were not being thrown for calling an undefined function. I added error_reporting(E_ALL); and ini_set('display_errors', 1); to the top of the file as well, and still no errors thrown. Either way, it works now. Thank you to everyone for the assistance.

php / mysql access denied with select into outfile

I have the following php code:
<?php
$hostname="db.";
$database="db..";
$username="db...";
$password="pw...";
$mysql = mysql_connect($hostname, $username, $password);
if(!$mysql)
echo 'Not conneted to the database...' . mysql_error() ;
else
echo 'Connected to the database...' ;
// select the appropriate database
$mysqldb = mysql_select_db( $database );
if(!$mysqldb)
die('Could not select the database...' . mysql_error());
else
echo '<br /><br />Connected to database...<br /><br />' ;
$chk_table_access = 'select * from table_name where 1';
$chk_access = mysql_query($chk_table_access);
echo $chk_table_access . '<br /><br />';
if (!$chk_access)
echo 'Could not access table: ' . mysql_error() ;
else
echo 'Table was accessed..<br /><br />' ;
$backup = 'SELECT * INTO OUTFILE "result.csv" FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY ';
$backup = $backup . "'" . '"' . "'" ;
$backup = $backup . ' FROM cities WHERE 1';
echo $backup . '<br /><br />';
$bk_success = mysql_query($backup);
if (!$bk_success)
echo 'The backup was not successful. Reason: ' . mysql_error();
?>
The program runs fine on localhost, but when I run it from my web site I get the following error: Access denied for user 'dbo????????'#'%' (using password: YES). The web help is not much help.
I do get the "Table was accessed.." message so I'm accessing the table okay. I do frwite to the directory every day without errors. I understand why it doesn't work in phpMyAdmin. I'm a little stumped. It's also the first question I've asked on this forum although I come here often for help. You guys (ladies included) rock.
Thanks in advance,
Steve
Your MySQL user apparently lacks the FILE privilege.
Does the MySQL server run on the same machine as the web server? If both servers run on different machines, you can stop right here: Even with FILE privilege, the output file would be created on the database server (and would probably inaccessible from the web server).

php IMAP connect to hotmail

I am using imap_open to connect to my hotmail account. Now I want to check list of all folders like inbox, junk, sent etc. using imap_list() like this.
<?php
$mbox = imap_open("{pop3.live.com:995/pop3/ssl}", "username", "password")
or die("can't connect: " . imap_last_error());
$boxes = imap_list($mbox, '{pop3.live.com:995/pop3/ssl}', '*');
print_r($boxes);
imap_close($mbox);
?>
but it shows only Inbox. Actually I want to check mails in the junk folder.
Try
$username = 'username';
$password = 'password';
$server = '{imap-mail.outlook.com:993/ssl}';
$connection = imap_open($server, $username, $password);
$mailboxes = imap_list($connection, $server,'*');
print_r(imap_errors());
print_r($mailboxes);
imap_close($connection);
It's worked for me and hope it'll help someone :)
This Code Is Not My Own As I Pulled It From php.net. But I Can Say It Will Work.
<?php
//check for new messages
$mailbox = imap_open("{localhost/pop3:110}INBOX",
"#username#","#password#");
// Check messages
$check = imap_check($mailbox);
print("<PRE>");
print("Date most recent message : " . $check->Date);
print("<BR>");
print("Connection type : " . $check->Driver);
print("<BR>");
print("Name of the mailbox : " . $check->Mailbox);
print("<BR>");
print("Number of messages : " . $check->Nmsgs);
print("<BR>");
print("Number of recent messages : " . $check->Recent);
print("<BR>");
print("</PRE>");
// show headers for messages
$index=1;
$header = imap_header($mailbox, $index);
print("<PRE>");
print("Header Date : " . $header->Date . "<BR>");
print("Header To : " . $header->to) . "<BR>";
print("Header From : " . $header->From . "<BR>");
print("Header cc : " . $header->cc . "<BR>");
print("Header ReplyTo : " . $header->ReplyTo . "<BR>");
print("Header Subject : " . $header->Subject . "<BR></PRE>");
print("<PRE>");
print(imap_body($mailbox,$index));
print("</PRE><HR>");
imap_close($mailbox);
?>
Hope That Helps A Bit.
change imap_list($mbox, '{pop3.live.com:995/pop3/ssl}', '*'); to imap_list($mbox, '{pop3.live.com}', '*');
no need for port or connection protocol...

Categories