having problems connecting to mysql db with php - php

I have a test db on godaddy, I have had a similar issue before but with the help of stackoverflow it was solved.. So I have actually used the same solution however now I am having a host of errors when I try to load my php file from the browser.
Warning: mysql_query() [function.mysql-query]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/97/8603797/html/countryQuery.php on line 14
Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/content/97/8603797/html/countryQuery.php on line 14
Warning: mysql_numrows(): supplied argument is not a valid MySQL result resource in /home/content/97/8603797/html/countryQuery.php on line 16
Warning: mysql_close(): no MySQL-Link resource supplied in /home/content/97/8603797/html/countryQuery.php on line 18
Database Output
I have read what the problem is and some of the things I have read suggest I am not connecting to the DB correctly.. but I am only doing what I have read/been told and dont really know what else I can do to solve the issue I am having...
this is my php code, if anyone has and suggestions or solutions I would greatly appreciate hearing from you.
<?
$hostname = 'mydatabasename.db.6666666.hostedresource.com';
$database = 'mydatabasename';
$username = 'myusername';
$password = 'secretsecret';
// establish a connection
$db = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$query="SELECT * FROM `Countries`";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
echo "<b><center>Database Output</center></b><br><br>";
$i=0;
while ($i < $num) {
$country=mysql_result($result);
echo "<b>$country<br>";
$i++;
}
?>
the out put should just be a list of the country names I have in the countrys table of my database.. which has values in it.

You are mixing PDO and mysql_* functions.
Try something like this:
$db = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$db->setAttribute(PDO::ATTR_AUTOCOMMIT, true);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql="SELECT * FROM `Countries`";
$numRows=$dbh->exec($sql);
echo "There were $numRows selected with:<b> $sql </b><br><br>";
$db=null;
unset($db);
When it comes to getting data from the PDO connection, I normally do something like this using the FETCH_INTO option:
$stmt = $db->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new userStructure);
// I do normally have a class matching the row I wan:
foreach($stmt as $userStructure)
{
$someObject->year=$userStructure->year;
$someObject->month=$userStructure->month;
unset($stmt);
}

Make sure that you include the port as well when using a PDO connection. This is looking like you are doing this in a hosted environment. Check the installation guide regarding the port used.

Related

PHP Warning: Error while sending INIT_DB packet. PID=3629

My automation code encountered a subject-like problem when calling a particular function.
It occurs randomly during execution, not immediately after execution, and after the problem occurs, the error "mysql_num_rows() expect parameters 1 to be resource, boolean given in" occurs and normal behavior is not performed.
The OS is Ubuntu 18.04.
PHP version is 5.6.40.
Mysql version is 5.7.38.
The problematic function code.
$conn = mysql_connect("127.0.0.1","ID","PW");
if($conn ==NULL)
{
echo "<script> alert(\" Error : DB 연결 에러입니다. 불편을 드려 죄송합니다. 관리자에게 문의 하십시요\"); </script>";
return $conn;
}
mysql_select_db("mysql");
mysql_query("set session character_set_connection=utf8;");
mysql_query("set session character_set_results=utf8;");
mysql_query("set session character_set_client=utf8;");
$dbname = "test_table";
$str = "select * from $dbname where 1";
$leak_result = mysql_query($str);
$leak_num1 = mysql_num_rows($leak_result);
Please give me a solution.
This error is appearing because of the maximum number of database connection requests have made.
Your Ubuntu 18 with PHP server it's making a lot of requests.
The "PID=3629" you read it's the Process Id that generates the error.
The method you are using mysql_query it's old and deprecated.
Now PHP uses mysqli method like this
$connect = mysqli_connect( $host, $user, $pass, $DBname );
$query = 'SELECT .... '; //here your query
$result = mysqli_query($connect,$query);
Like said in comments, if there's an error mysqli_query gives back a false result
PHP OFFICIAL SITE
If you want a more complete answer on the error use the mysqli_error() function.
Good luck

mysqli_error() expects parameter 1 to be mysqli, null given

I have a a form that pulls data from a database(mysql to be specific) and echos the data into the value section of <input> tags. It doesn't seem to be working I have coded a view section of my website to do the same thing but from a different table in my database. I use the same code to make making changes easy and if another developer works on my site in the future. Anyway it doesn't seem to be working I'm not sure why though.
The full error I get:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/caseol5/public_html/jj/admin/news_update.php on line 9
Here is line 9 that the error is referring to:
$result = mysqli_query($link,$sql);
I know that both of those function are not null as I did:
echo $link
echo $sql
before that line after I started feting the error and they both are not null.
Here is the full code segment:
$nid = $_GET['nid'];
include ("../sql/dbConnect.php");
$sql = "SELECT * FROM jj_news WHERE news_id = $nid";
echo "<p>The SQL Command: $sql </p>";
echo "<p>Link: $link </p>";
$result = mysqli_query($link,$sql);
if (!$result)
{
echo "<h1>You have encountered a problem with the update.</h1>";
die( "<h2>" . mysqli_error($link) . "</h2>") ;
}
$row = mysqli_fetch_array($result);
$ntitle = $row['news_title'];
$ntline = $row['news_titleline'];
$ndesc = $row['news_desc'];
$nother = $row['news_other'];
I have looked into mysqli_query and I can't find anything I'm missing. I have also tired breaking the code down (and running parts of it and it gives the same error. My guess is it something small that I missed. I've looked at other question on this site that do that are a little similar but none seem to help. I've been looking at this for a while now and need another pair of eyes.
Update
As requested the contents of my dbconnect.php file:
$hostname = "localhost";
$username = "caseol5_jjoes";
$database = "caseol5_jj_site";
$password = "password1";
$link = mysqli_connect($hostname, $username, $password, $database);
$link = mysqli_connect($hostname,$username,$password,$database) or die("Error " . mysqli_error($link));
if (!$link)
{
echo "We have a problem!";
}
As clearly stated in the error message, mysqli_querydocs expects the first parameter to be a mysqli resource. In your case, this parameter is called $link but it holds a null value. A proper mysqli resource is normally obtained from connecting with the database by making use of mysqli_connectdocs
I expect the ../sql/dbConnect.php file holds the logic to connect with the database. Verify whether the $link variable is indeed initialized there. If it's not there, try to find an occurrence of mysqli_connect - maybe the resource is set to a different variable.
Without knowing what exactly is in ../sql/dbConnect.php, your problem right now is that you do not have a valid mysqli resource to use for mysqli_query.

Warning: mysqli_query(): Couldn't fetch mysqli in C:\ ... on line 13

although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.

PHP - How do I tell why mssql_connect() didn't work?

I'm using PHP 5.2, and normally mssql_connect works fine - but I'm trying to connect to a new MS SQL server, and it won't connect. I've probably got something wrong in the connection details or credentials, but I have no way of telling as I can't get an error message.
The mssql_connect() method returns false, and no connection is available.
mssql_get_last_message() returns nothing - so how do I tell why my connection failed?
Anyone got any ideas?
In MySQL I'd use mysql_error - but there doesn't seem to be an equivalent for ms_sql.
[EDIT]
This question is not a duplicate of "MSSQL_CONNECT returns nothing - no error but no response either" - I'm using php 5.2, and the code works fine for other connection details. I need to figure out how to output what the connection error is - not what the problem is with connecting.
[EDIT2]
To clarify:
the extension is enabled on the server
the code works fine for existing connection details
I am using new connection details and don't know if the hostname or password is wrong
I know the code isn't connecting because I check to see if it's connected
I want to find out the connection error - like you can with MySQL.
Sample code below:
$db_connection = mssql_connect($host, $user, $pass);
$db = mssql_select_db($dbname, $db_connection);
if (!$db_connection) {
echo "No connection";
echo "connection failed because: " . ???????;
die;
}
What do I put in place of ??????? to get the connection error message?
//Database Connection by PDO (MS SQL Server, PHP)
$serverName='localhost';
$database='TreeDB';
$uid='sa';
$pwd='sa*5234';
$dbo = new PDO("sqlsrv:server=$serverName ; Database = $database;ConnectionPooling=0", $uid, $pwd);
//var_dump($dbo);
//Database Query
$sql = "SELECT node.id, node.name, COUNT(parent.id) - 1 AS depth, node.lft, node.rgt
FROM dbo.OrgTree AS node CROSS JOIN dbo.OrgTree AS parent
WHERE (node.lft BETWEEN parent.lft AND parent.rgt)
GROUP BY node.id, node.name, node.lft, node.rgt
ORDER BY node.lft";
//Execute Query
$sql = $dbo->prepare($sql);
$sql->execute();
$qry = $sql->fetchAll();
foreach ($qry as $fetch)
{
$tree[] = $fetch;
}
//print_r($tree);
See below
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'KALLESPC\SQLEXPRESS';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
?>
In this way you can display error if connection fails.
Ref: http://www.php.net/manual/en/function.mssql-connect.php

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

Categories