mysql_connect in php 5.6 + [duplicate] - php

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.

Related

Inserting ID from primary col to another table

I want to insert 2 tables columns ids to another table
I got the query but there is the annoying error.
I tried to solve this problem for hours none worked :(
This code:
$query = "INSERT INTO
groups(
group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count
)
VALUES(
$group_shcool_id,
$group_teacher_id,
'$group_name',
'$group_note',
'$group_system',
'$group_students_count'
)";
this old:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
mysqli_query($con, "SET NAMES 'utf8'");
}
?>
this new:
<?php
// if you are using php just don't forget to add php tags though
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
//using try catch statements
try{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
?>
its connects successfully but all my code use the old one, how to change to convert it? I dont know what pdo I like to learn it, it seems more pro type, but is there solution for this site only using mysqli?
sorry for the long post this is my 1st one, dont know how to explain enough
Thanks
give this error :
QUERY FAILED .You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , 'test', '', 'test' at line 11
I thought it will work fine like this but I think the problem with the query syntax.
Just an advice try to use PDO prepared statements example below:
$query = "INSERT INTO groups(group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count)
VALUES (:gsid,:gtid,:gname,:gnote,:gsystem,:gstudcount)";
//assuming $conn is your object variable name for database connection
$stmnt = $conn->prepare($query);
$stmnt->execute(array(':gsid'=>$group_school_id,
':gtid'=>$group_teacher_id,
':gname'=>$group_name,
':gnote'=>$group_note,
':gsystem'=>$group_system,
':gstudcount'=>$group_students_count));
//to check if you have inserted data into your table
$rows = $stmnt->rowCount();
echo "Inserted ".$rows." row";
the :gsid are placeholders for your variables, also make sure that each variable passed are inline with column datatypes in your database
//if you are using php just don't forget to add php tags though
$dbhost = "localhost";
$dbname = "whatevername";
$dbuser = "root";
$dbpass = "";
//using try catch statements
try{
$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}

Error in MySQL and PHP [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 6 years ago.
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead.
connect.php
error in:
<?php function connections(){
$user="root";
$pass="";
$server="localhost";
$db="db";
$con=mysql_connect($server,$user,$pass) or die ('Connection failed: '.mysql_error());
mysql_select_db($db,$con) or die ('Could db: '.mysql_error());
return $con;
}
?>
insertcase.php
error in:
$con=connections();
$query="insert into caso values ('','$date','name')";
$cierto=mysql_query($query,$con);
if(!$cierto){
echo "No saved";
}
else {
$query= mysql_query("SELECT ##identity AS id ");
if ($row = mysql_fetch_row($query))
{
$id = trim($row[0]);
}
echo '<script>alert (" tickect is: '.$id.'"); window.location="../index.php";</script>';
}
please help... :)
Use PDO to connect to a mysql server.
here is an example.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

No database selected help me solve this [duplicate]

This question already has answers here:
PHP "No Database Selected"
(2 answers)
Closed 8 years ago.
hey everyone what's wrong with this :( i get no database selected .. what seems to be the problem ? damn i can't get this right.
<?php
require_once('db.php');
function getLanguage() {
global $db;
global $conn;
$sql = "SELECT * FROM books.languages ORDER BY name ASC";
$db = mysql_connect($hostname, $username, $password);
$rs = mysql_query($sql, $db) or die(mysql_error());
$rows = mysql_fetch_assoc($rs);
$tot_rows = mysql_num_rows($rs);
if($tot_rows > 0){
?>
Problem is no database is selected (didn't I see that in your question ?)
Where is your call to mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )?
It should be after the connect.
$db = mysql_connect($hostname, $username, $password);
mysql_select_db("your_database_name");
$rs = mysql_query($sql, $db) or die(mysql_error());
(obviously you should have error checking too...)
Maybe something like the following will help? I am using MySQLi as MySQL is deprecated.
db.php
<?php
// CONNECT TO THE DATABASE
$DB_NAME = 'database';
$DB_HOST = 'host';
$DB_USER = 'username';
$DB_PASS = 'password';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
Then use the following to query your database.
<?php
require_once('db.php');
$sql = "SELECT * FROM tablename";
$rs = $mysqli->query($sql) or die($mysqli->error.__LINE__);
if($rs->num_rows > 0) {
while($row = $rs->fetch_assoc()) {
//Do Something
}
}
else {
echo 'NO RESULTS';
}
mysqli_close($mysqli);
?>

mysql_select_db returns false while mysql_error returns nothing

I'm trying to connect to a database, but mysql_select_db always returns false. If I just use the first parameter of mysql_select I get the error: Access denied for user ''#'localhost' to database 'newboston', if I enter the connection link as the second parameter mysql_error returns nothing. Anyone knows what's going on?
<?php
$dbServer = 'localhost';
$dbUserName = 'root';
$dbPassword = 'password';
$database = 'newboston';
$db = mysqli_connect($dbServer, $dbUserName, $dbPassword);
$connectFailed = 'Could not connect to ' . $dbServer . '.';
if($db)
{
if(mysql_select_db($database, $db))
{
echo 'Connected to ' . $database;
}
else
{
echo 'Could not connect to ' . $database;
die(mysql_error());
}
}
else
{
echo $connectFailed;
}
?>
You're mixing mysql and mysqli:
$db = mysqli_connect($dbServer, $dbUserName, $dbPassword);
should be:
$db = mysql_connect($dbServer, $dbUserName, $dbPassword);
(actually you should be using mysqli as mysql is deprecated).
You're mixing mysqli_* functions with mysql_* functions.
May I suggest learning PDO MySQL instead?

connect to sql database with 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

Categories