connect to sql database with php - php

Im trying to connect to sql database with PHP.For some reason when i run the code i am getting below error.
Parse error: syntax error, unexpected '$result' (T_VARIABLE) in C:\xampp2\htdocs
\tutorials\abb.php on line 13
My Code is this...
$user = 'root' ;
$pass = 'xcvsdffd' ;
$db = 'testdb' ;
$con = new mysqli('localhost', $user , $pass , $db) or die("UNABLE TO CONNECT");
$selected = mysql_select_db($db,con)
$result = mysql_query("SELECT * FROM test");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name33'}."
".$row{'year'}."<br>";
}
//close the connection and recordset objects freeing up resources
$result->Close();
$con->Close();
$result = null;
$con = null;
?>

There are two reasons which was the reason for your errors..
1.
You missed a semicolon ; and a $ sign. Below is valid one.
$selected = mysql_select_db($db,$con); //Replace this with your existing line.
2.
You are mixing mysql_* and mysqli_*
Sidenote:
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
The PDO way...
<?php
$dsn = 'mysql:dbname=testdb;host=localhost';
$user = 'root';
$password = 'xcvsdffd';
try
{
$dbh = new PDO($dsn, $user, $password ,array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
For more information.. read the PHP Manual. or use PreparedStatements in MySQLi

Mysqli works with MySQL version 4.1.13 or newer; if your version is old then u should connect your db the old way like this:
$con=mysql_connect("localhost","root","pass");
mysql_select_db("database_name",$con);

They always tell me that MySQL command is now depreciated or something. That's why it's a good practice to use PDO or MySQLI. It's easy to use, if you'll appreciate it's use.
Now going to your code:
$connection = new mysqli("localhost","user","password","database name");
$selectDatabase = mysqli_select_db($connection,"database name");
$connection->query ("SELECT * FROM test");
Hope this helps

Try this below , if you are creating mysqli connection then you dont have to use mysql_select_db($db,con) for again select database. or use semicolon after this line
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
/* change db to world db */
$mysqli->select_db("world");
/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);
$result->close();
}
$mysqli->close();
?>
Reference

there might be a semicolon missing in a line .
mysql_select_db($db,$con);

Try this
<?php
$username = 'root';
$pass = 'pass';
$db = 'db';
$link = mysqli_connect('localhost',$username,$pass,$db);
if(!link){
echo "Not Connected to DB" . mysqli_connect_error();
$result = mysqli_query($link, "SELECT * FROM test");
while($row = mysqli_fetch_array($result)){
echo "ID: " . $row['id'];
echo "Name: " . $row['name33'];
echo "Year: " . $row['year'];
}
?>
Querying in PHP must be consistent, meaning if you use mysqli you should use it throughout the PHP file, and if you use mysqli you must also use it throughout the PHP file. mysqli and mysql also has different code constructions. So search on the web for their proper construction. Hope this helps

Related

IIS, MS SQL and PHP - SQL select in PHP not working

I have a local MS SQL Database, and a web PHP application on IIS on my server.
On IIS I have successfully connected PHP and my MS SQL database (added connection strings and i see my tables)
But, when I use any SQL select in the PHP web application, it does not work. No data is displayed, or any erros, for example :
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=dbname;host=localhost';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$results = mysql_query("SELECT id FROM users");
while($row = mysql_fetch_array($results)) {
$name = $row['id']
?>
<tr>
<td><?php echo '$name'?></td>
</tr>
<?php
}
?>
</tbody>
</table>
follow like this for pdo connection
$sql = $dbh->prepare("SELECT id FROM users");
$sql->execute();
while($result = $sql->fetch(PDO::FETCH_ASSOC)){
?>
<tr>
<td><?php echo $result['name'];?></td>
</tr>
<?php } ?>
Please follow that code:
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt =
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
$stmt = $pdo->query('SELECT name FROM users');
while ($row = $stmt->fetch())
{
echo $row['name'] . "\n";
}
MS SQL (or SqlSrv) and MySql are not working on the sames drivers. You have to know which one you are using and the find PHP functions ables to deal with it.
Note: PHP Extension for using driver must be installed on your server and activated on php.ini file
For MySql do not use mysql_xxx() deprecated functions, prefer mysqli_xxx() to them.
You can find here docs and samples code for both mysql & mssql php functions :
MySql :
http://php.net/mysqli_connect
php.net/mysqli_fetch_array
SqlSrv :
http://php.net/sqlsrv_connect
php.net/sqlsrv_fetch_array
So what is your database engine ?
Hope that'll helps you, cheers
Mixing the apis would not work - use only PDO methods like this perhaps
/* Connect to a MySQL database using driver invocation */
try {
/* mysql server */
/* $dsn = 'mysql:dbname=dbname;host=localhost'; */
/* MS SQL Server */
$dsn = 'sqlsrv:Database=dbname;Server=localhost';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$sql='select * from users';
$results=$dbh->query( $sql );
if( $results ){
while( $rs=$results->fetch( PDO::FETCH_OBJ ) ){
echo "<tr><td>{$rs->name}</td></tr>";
}
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Now working great also with select, with this code :
<?php
$serverName = "AC-CLOUD"; //serverName\instanceName
$connectionInfo = array( "Database"=>"Data", "UID"=>"sa", "PWD"=>"Masterkey2010");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Code, Name FROM StoreCards";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['Code'].", ".$row['Name']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
How now i set this two values into table? this is last point. thank you for your patience and time.

mysql_connect in php 5.6 + [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 6 years ago.
I was using PHP 5.4 in Godaddy Hosting. I have one PHP script which was working fine in it. Now I have changed Hosting and New Hosting company Provide PHP 5.6. I do not PHP coding. I am getting error in my script as below
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home4/z4g9f1v6/public_html/mydomain.com/folder/config.php on line 7
My Configure file is like below
$mysql_hostname = "localhost";
$mysql_user = "dbuser";
$mysql_password = "dbpass";
$mysql_database = "dbname";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
and I am using it in my Search.php like below
include("config.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');
$q=$_POST['q'];
$q=mysql_escape_string($q);
$q_fix=str_replace(" ","%",$q); // Space replacing with %
$sql=mysql_query("SELECT qu_text FROM quotes WHERE qu_text LIKE '%$q%'");
}while($row=mysql_fetch_array($sql)){$title=$row['qu_text'];
Please help me. How can I solve the issue ?
Thanks
For Myqli connection
$mysql_hostname = "localhost";
$mysql_user = "dbuser";
$mysql_password = "dbpass";
$mysql_database = "dbname";
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password,$mysql_database) or die("Could not connect database");
For Query Please follow this answer How can I prevent SQL injection in PHP? it's really nice.
You could use this for query
$sql=sprintf("SELECT qu_text FROM `quotes` WHERE qu_text LIKE '%s%%'"),mysqli_real_escape_string($bd,$q));
$fetch= mysqli_query($bd,$sql) or die(mysql_error());
while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
//Your Result
}
Most of mysql_ syntax you could use with mysqli_
As PHP is becoming a Object Oriented Scripting language, it will be better to make use of PDOs to make connections to Database and perform the operations, for this you have a give a little bit of more effort. Like making Entity Classes for each table's(each column as variable), this is the only hectic part but it will make the program more secure and more readable.
I am just giving the code for connecting to database and retrieving the dataset :
1. DBConfig.php
$dsn = 'mysql:dbname=<database-name>;host=<host-name>';
$user = '<user-name>';
$password = '<password>';
try
{
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
2. Search.php
require_once 'DBConfig.php'; //If DBConnection is not made in same file
require_once '<name-of-entity-class>.php';
$q = (isset($_POST['q']) && !empty($_POST['q'])) ? $_POST['q'] : NULL;
try
{
$query = "SELECT qu_text FROM quotes WHERE qu_text LIKE :q";
$stmt = $conn->prepare($query);
$stmt->bindValue(':q', $q, PDO::PARAM_STR);
$stmt->execute();
while($row = $stmt->fetch())
{
$dataset[] = new <name-of-entity-class>($row);
}
if(!empty($dataset))
{
foreach ($dataset as $data)
{
echo '<p>';
echo $data->get<var-name>;
echo '</p>';
}
}
else
echo 'empty database';
}
catch (Exception $ex)
{
echo 'Some error occured: ' . $e->getMessage();
}
Thanks and Regards.

Query MySQL with PHP

I am trying to query a MySQL database with PHP and return the results as JSON. I'm new to PHP and web development so I'm not sure what I'm doing wrong. I've set up the database using MAMP. My parameters are being printed but I'm not getting the JSON. I've gotten this far with the help of a tutorial.
EDIT: I just went into phpMyAdmin to make sure it was working and when I click on Server:localhost:8889, a window pops up that says Error in processing request. Error code 404.
I'm thinking this is the problem, I'm just not sure why it isn't working. I may reinstall MAMP.
<?php
$user = 'root';
$password = 'root';
$db = 'TestDB';
$host = '127.0.0.1';
$port = '8889';
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
$membership_number = filter_input(INPUT_GET, 'membership_number');
echo $first_name;
echo $last_name;
echo $membership_number;
// Create connection
// $con = mysqli_connect("localhost", "root", "root", "TestDB");
// $con = mysqli_connect("localhost", "root", "root", "TestDB", "8889", $socket);
$link = mysqli_init();
$con = mysqli_real_connect($link, $host, $user, $password, $db, $port);
// Check connection
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = \'$first_name\' and LAST_NAME = \'$last_name\' and MEMBERSHIP_NUMBER = \'$membership_number\'";
$result = mysqli_query($con, $sql);
if(!$result) {
die('Query failed: ' . mysqli_error());
}
// Check for results
// if ($result = mysqli_query($con, $sql)) {
if($result) {
// If there are results, create results array and a temporary one to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
// while($row = $result->fetch_object()) {
while($row = mysqli_fetch_object($result)) {
// Add each row to the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo $tempArray;
echo $resultArray;
echo $result;
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
You need to change you $sql variable to remove the escapes on the single quotes. They register as part of the string because you are using double-quotes to wrap it. Basically, you're telling the database to run the query "SELECT * FROM NAME WHERE FIRST_NAME = \'John\' and LAST_NAME = \'Smith\' and MEMBERSHIP_NUMBER = \'VRX78435\'". This will error if you run it directly because the escape characters are not escaping.
$sql = "SELECT * FROM NAME WHERE FIRST_NAME = '$first_name' and LAST_NAME = '$last_name' and MEMBERSHIP_NUMBER = '$membership_number'";
That should fix it for you.
There may also be an issue with your connection to the server. mysqli_query() uses the results of mysqli_connect() to run the query. mysqli_real_connect() only returns a boolean value, so it is invalid for this particular use (at least it failed to work on my server).
This would be a simple matter of replacing the $con and then you can drop the $link variable.
$con = mysqli_connect($host, $user, $password, $db, $port);
These changes, and assuming the $first_name, $last_name, and $membership_number are all valid, allowed your script to run for me, so I hope this helps.
Seems you are using procedural style coding
Instead of
while($row = $result->fetch_object()) {
You need mysqli_fetch_object in procedural style
while($row = mysqli_fetch_object($result)) {

Error occurred ... no database selected

I'm trying to connect to a database, check a column for whether a value exists or not, then execute a function based on whether or not that value exists.
Here's my code.
$con = mysql_connect('localhost','root','','users');
$sql = "SELECT * FROM allUsers WHERE username = '".mysql_real_escape_string($_POST["username"]) . "'";
$result = mysql_query($sql,$con) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
if ($count != 0){
echo "Username is already taken";
echo "$count";
mysql_close($con);
}
else{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
The thrown error is:
Error occurred in [SELECT * FROM allUsers WHERE username = 'Admin']: No database selected.
I'm almost entirely sure that it comes from the $result line, but haven't a clue as to why.
I feel like this is a simple solution, and I'm just missing something minor.
I'm very new to MySQL (today is my first day, actually), so please keep solutions as simple as possible.
You forgot to call mysql_select_db after connecting:
$con = mysql_connect('localhost','root','');
mysql_select_db('users', $con);
Unlike MySQLi or PDO, mysql_* libraries does not take database as argument on the connection string, however if you were to migrate to either MySQLi or PDO.
MySQLi:
$con = new mysqli('localhost', 'root', '', 'users');
PDO:
$con = new PDO('mysql:host=localhost;dbname=users', 'root', '');
In MySQLi your code would look like this:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$con = mysqli_connect($host,$user,$pass,$database);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$stmt = $con->prepare("SELECT * FROM allUsers WHERE username = ? LIMIT 1");
$stmt->bind_param('s',$_POST["username"]);
if (!$stmt->execute())
die('Failed to excute with error ' . $con->error);
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count > 0)
{
echo "Username is already taken.";
}
else
{
createUser($_POST["name"],$_POST["username"],$_POST["password"],$_POST["email"]);
}
I think your error is quite obvious, you need to specify the database you want.
mysql_select_db("databaseName", $con);
With that taken care of, please, please don't use mysql_ libraries the are vulnerable to SQL injection and will soon be removed.

checking if a database exists

The code below works fine except it throws a warning when connecting to a database that does not exist. This works fine in product where errors are off, but I would rather not have errors if I don't need to.
function cpanel_db_connect($dbname) {
// normalize
$dbname = convert_to_slug($dbname);
$dbname = CPANEL_USER . '_' . $dbname;
$dbuser = CPANEL_USER . '_' . CPANEL_DB_USER;
// connnect database
$mysqli = new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
if ($mysqli->connect_error) {
return false;
}
return $mysqli;
}
It's not a good practice to suppress warnings/errors using the # sign in PHP. You could accidentally suppress an invalid username or password message and you would never know it.
A more appropriate way of checking if the database exists is creating a new instance of Mysql or Mysqli (without specifying the default database) and executing the following query (similar to Marc B's comment):
SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME='my_database_name'
Then you can check the value of the key exists to see if the database is there or not.
Here's a sample code:
// statement to execute
$sql = 'SELECT COUNT(*) AS `exists` FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMATA.SCHEMA_NAME="my_database_name"';
// execute the statement
$query = $mysqli->query($sql);
// extract the value
$row = $query->fetch_object();
$dbExists = (bool) $row->exists;
It is a bit longer but it's safer.
$mysqli = #new mysqli(CPANEL_DB_HOST, $dbuser, CPANEL_DB_PASS, $dbname);
The above works!
This works, just replace $dbname in this code:
if (empty (mysql_fetch_array(mysql_query("SHOW DATABASES LIKE '$dbname' ")))){
echo "DB does Not exist"; }else{ echo "DB exists!";}
Updating to MYSQLI:
$conn = new mysqli('localhost', 'root', '');
$dbname='test';
if (empty (mysqli_fetch_array(mysqli_query($conn,"SHOW DATABASES LIKE '$dbname'"))))
{
echo "DB not exist<br>";
}
else
{
echo "DB exist<br>";
}
Here's how to connect to DB server without selecting a DB, and only connecting if DB exists:
$mysqli = new mysqli($db_biz['server'], $db_biz['user'], $db_biz['password']);
$query = 'SHOW DATABASES LIKE "' . $db_biz['dbName'] . '"';
$resShowBizDB = $mysqli->query($query);
if ($resShowBizDB->num_rows == 1) { //Found database
$mysqli->select_db($db_biz['dbName']);
if ($mysqli->connect_errno) { //Check for errors
var_dump($mysqli);
echo "Failed to connect to biz database: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset('utf8');
} else { //Didn't find DB
die('<h1>ERROR</h1><p>Found no database</p>');
}

Categories