PDO code not working - php

i am new to PDO.. i tried out some online tutorials and found some step-by-step guides. i am using WAMP, i created a database named "try" with table named "books".
Now in my index.php i wrote:
<?php
$host = "localhost:3306";
$db = "try";
$user = "clyde";
$pass = "moonfang";
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$sql = "SELECT * FROM books";
$q = $conn->query($sql) or die("failed!");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo $r['title'];
}
?>
Now whenever i load localhost on my browser i see these errors;
i dont understand the problem.. :-(

According to several examples it seems that PDO prefers the host and the port in the dsn for itself:
$host = "localhost";
$port = 3307;
$conn = new PDO("mysql:host=$host;port=$port;dbname=$db",$user,$pass);
Here's the PHP manual for the PDO MySQL DSN. Note the "port" part.

The problem is that the target machine actively refused [the connection].
Therefore you have to check if usernames/passwords/access-rights to the database server are all OK; including IP/host and port/firewall settings.

Line 8 where error occurs is $q = $conn->query($sql) or die("failed!"); This line mixes mysql_ and PDO and is not required.
The code should look like
$sql = "SELECT * FROM books";
while($r = $sql->fetch(PDO::FETCH_ASSOC)){
echo $r['title'];
}
You should also incorporate PDO error handling
`

Related

How do you fetch from a mysql database?

I'm relatively new to any type of programming or coding. I'm not quite understanding why no matter what adjustments I make to my php file I can't seem to pull any data from a table.
Here is a link to the table: https://i.gyazo.com/4ad5e860895014c49dbe0539c38cdec2.png
Above is the test table I have been trying to use. From what I can understand I'm connecting to the database okay, but all of my problems come after the connection. Also, I'm using php 7.0 so a lot of the information I'm finding online has not been helpful.
If there is something glaringly wrong with my table or in my code, please let me know.
Here is my code:
'''
//Set Variables
$serverName = "localhost";
$userName = "root";
$password = "";
$databaseName = "test";
//Create Connection
$connection = mysqli_connect($serverName,$userName,$password,$databaseName);
//Check Connection
if(!$connection){
die("Connection failed: ".mysqli_connect_error());
}
echo "Connected successfully <br>";
//Fetch Data
$query = "SELECT * from table1";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf ($row[1], $row[2]);
mysqli_free_result($result);
mysqli_close($connection);
I figured out the issue a few hours ago. The code I had posted would have worked perfectly fine if I was connecting to the port for MySQL rather than MariaDB. Didn't realize that the port that MariaDB was connected to was the default.
MariaDB by default was port 3306, but MySQL was 3308. After specifying 'localhost:3308' I was able to start properly pulling rows from my tables.

query doesn't working using php

I am new in Php and MYsql,
I am trying to create a simple query using which contain a variable using php.
however I think I am not writing the querty correctly with the variable since the result of this query is 0.
would be happy for assistance here is my code:
<?php
$phone = $_GET['phone'];
echo $phone;
$query = "SELECT * FROM `APPUsers` WHERE `Phone` LIKE "."'".$phone."' ";
echo $query;
$result = mysqli_query($mysqli, $query);
echo mysqli_num_rows($result);
?>
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = $conn->query($sql);
Above there is a fast solution , but it is not safe ,
because is vulnerable to injection ...
Below let's see how to do it and why to do it in this way
It is a good practice to store sensible information in a separate file
out of the document root , it means will be not accesible from the web .
So let's create a file configDB.ini for example and put in db informations
servername = something;
username = something;
password = something;
dbname = something;
Once did it we can create a script called dbconn.php and import the file with credentials ,
in this way there is an abstraction between credentials and connection .
in dbconn.php :
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
We can even improve the code connecting to db only once and use the same connection all the time we need query .
function db_connect() {
// static will not connect more than once
static $conn;
if(!isset($conn)) {
$config = parse_ini_file('../configDB.ini');
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
return $conn;
}
...
$conn = db_connect();
$sql = "SELECT * FROM APPUsers WHERE Phone LIKE '%$phone%'";
$result = mysqli_query($conn,$sql);
In the end let's say something about mysqli_query
Reasons why you should use MySQLi extension instead of the MySQL extension are many:
from PHP 5.5.0 mysql is deprecated and was introduced mysqli
Why choose mysqli (strenghts)
object oriented
prepared statements
many features
no injection
Do you connect to the database?
The apostrophes around APPUsers and Phone might not be the right ones, as they are not the single apostrophes but some weird squiggly ones.
Try this :
$query = "SELECT * FROM 'APPUsers' WHERE 'Phone' LIKE '".$phone."' ";

Overcoming PHP/SQL Server encoding inconsistency

Following this blog post, I managed to connect to a MSSQL Server form PHP/CentOS machine. I can get result, however I can not use comparison in the where clause. I should be due to different encoding. Here is my code:
$db = new PDO("odbc:USERS", "username", "password");
$sql = "SELECT top 1 name FROM user where name='تست'";
$stmt = $db->prepare($sql);
$result = $stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
var_dump($row);
Also using $name = mb_convert_encoding('تست', 'utf16'); (also 'UCS-2LE' encoding) Was not helpful. How config PHP/MSSQL to use a single encoding?

connecting to a database in mysql using php

Hey i'm new to php/mysql and i'm trying to execute a very simple php code that will display the contents of the table. I feel like the code is perfect, and i get no error messages, but for some reason it doesn't work. I know you guys hate debugging questions like this, but
if you could help i'd appreciate it. here's the php.
<?php
$conn=mysql_connect("localhost","demo","abc") or die(mysql_error());
mysql_select_db("practice");
$sql="SELECT*FROM contact";
$result=mysql_query($sql,$conn) or die(mysql_error());
while($row=mysql_fetch_assoc($result)){
foreach($row as $name => $value){
print "$name: $value <br>\n";
} //end foreach
print "<br /> \n";
} //end while
?>
You're using the old mysql library which is a no no
Get comfy with the Mysqli Extension for all your database access needs. I'll even refactor this a bit for you.
$conn = new Mysqli('localhost', 'demo', 'abc', 'practice');
$sql = "SELECT*FROM contact";
$results = $conn->query($sql);
while($row = $results->fetch_assoc())
{
var_dump($row);
}
edit: JimiDini posted a link that you should definitely read. http://phptherightway.com/
try this
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// or if you want to enable all PHP error reports, use this code below and comment out the one above
//error_reporting(-1);
$dbhost = 'localhost';// Server name (usually localhost)
$dbuser = 'user';// SQL Username (Make sure the user has access to the database!).
$dbpass = 'password';// SQL Password.
$dbase = 'db name';// SQL Database Name.
//connection to the database
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die(mysql_error());
$sql = "SELECT * FROM `contact`";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
print_r($row);
}
but you should use mysqli in the future

Cannot get my php to process sqlsrv_connect on my GoDaddy Server

I have an android app that i am trying to get connected to my SQL Server.
I have tried countless ways of getting it to work by get a error on my sqlsrv_connect.
Here is the php im tyring to use. I have replaces my read server/credentials with *
<?php
$myServer = "***";
$myUser = "***";
$myPass = "***";
$myDB = "***";
//connection to the database
$conn = sqlsrv_connect($myServer, array('UID'=>$myUser, 'PWD'=>$myPass, 'Database'=>$myDB));
$_GET['search'];
//declare the SQL statement that will query the database
$query = "SELECT * FROM dbo.JD";
$data = sqlsrv_query($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
$result[] = $row;
}
}while ( sqlsrv_next_result($data) );
echo(json_encode($result));
sqlsrv_free_stmt($data);
mssql_close($dbhandle);
?>
When processing on a php online test i get this error
Fatal error: Call to undefined function sqlsrv_connect() in [...][...]on line 7
Here my my php info
http://www.bakerabilene.com/phpinfo.php
It shows sqlsrv as a Registered PHP Streams so I don't understand why its not working.
I have also stripped my php down to where it just makes the connection to see if anything was causing the issue, but it still gives me that same error.
I am positive my server/user/pass/db are correct because i use the exact same credentials on my aspx webpage to access SQL server.
Check if the Native SQL Driver (Microsoft Drivers 3.0 for PHP for SQL Server) is installed . Have you asked the Godaddy Team about this ?

Categories