Error in MySQL and PHP [duplicate] - php

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();
}
?>

Related

Database connect in PHP 7 [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
but i do not understand what i am doing wrong and why it is not working ?
Seems like it connects with DB, but it wont update DB table.
My PHP code
<?php
$host = 'localhost';
$db_name = 'db_name';
$db_user = 'user';
$db_password = 'password';
$con = mysqli_connect($host, $db_user, $db_password, $db_name);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
function _VoteReward($custom)
{
$sql = "UPDATE `users` SET `gold` = `gold` + 50000 WHERE `id` = '".$custom."' ";
mysqli_query($con, $sql);
}
$custom = $_POST["custom"];
$key = $_POST["key"];
$result = false;
if (($custom > 0) && ($key == 'key'))
{
$result = true;
_VoteReward($custom);
}
mysqli_close($con);
?>
The above code does actually produce a connection to the database. However, the resulting connection does need to be checked for errors. Typically by the following:
if(!$con)
{ // creation of the connection object failed
die("connection object not created: ".mysqli_error($con));
}
if (mysqli_connect_errno())
{ // creation of the connection object has some other error
die("Connect failed: ".mysqli_connect_errno()." : ". mysqli_connect_error());
}

Mysql & Php Database connection error

When ever I use php to connect to my database I get a sudden error saying "database connection failed" is there anyway to fix this its for a login and register screen. Thanks to anyone who help...
<?php
$connection = mysqli_connect('localhost', 'root','','test');
if (!$connection){
die("Database Connection Failed" . mysqli_error($connection));
}
$select_db = mysqli_select_db($connection, 'test');
if (!$select_db){
die("Database Selection Failed" . mysqli_error($connection));
}
<?php
//
require('database.php');
$connection = mysqli_connect('localhost', 'root','','test');
// If the values are posted, insert them into the database.
if (isset($_POST['Register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO `user` (username, email, password) VALUES ('$username', '$email', '$password')";
//echo $query;
$result=mysqli_query($connection,$query);
if($result){
$smsg = "User Created Successfully.";
}else{
$fmsg ="User Registration Failed";
}
}
?>
Connection to a database with php requires 4 parameters (host, data base user, password, data base name, passwd), it's better nowadays to use db object instead of procedural "old" behaviour:
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli("localhost", $dbUser, $passwd, $dbName);
if (!$mysqli->set_charset("utf8")) $msg = "error charset mySQLi"; else $msg = "Set UTF-8 ok";
return $mysqli;
}
catch (Exception $mysqlin){
echo "Error stablishing connection with database ".$mysqlin->getMessage();
}
}
then you can connect easily as follows:
$sql = "SELECT * FROM users;";
if(!$result = connection()->query($sql)) echo "db query error"; else "query ok";
$rs = mysqli_fetch_assoc($result);
//do whatever and, to get next line of results:
if($rs!=''){
$rs = mysqli_fetch_assoc($result);
}
So you get a row of the results on $rs[] array.
EDIT: You'll need to apply security, this is a simple connection without regarding on it. Check mysqli bind params on php official webpage for it:
http://php.net/manual/en/mysqli-stmt.bind-param.php
Hope it helps

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.

how to convert mysqli_set_charset($conn,"utf8") into PDO format in MYSQL?

I trying to solve the UTF8 problem. So far i manage to test out and it works in mysqli connection.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tesddddt";
$conn = mysqli_connect($servername, $username, $password, $dbname);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM customer";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["uid"]. " - Name: " . $row["username"]. " " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
I manage to Insert and Select data with characters shown in it's language format correctly with the above coding.
However, when I try to do it in PDO , it shows 1 error when I insert data.
public function __construct(){
try {
$conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user_name, $this->db_pass);
mysqli_set_charset($conn,"utf8"); // <- added here
$this->conn=$conn;
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
I got this error
Warning: mysqli_set_charset() expects parameter 1 to be mysqli, object given in...
My php project is using PDO and hence need to get this work in PDO format. Anyone know how to settle this?
You try to connect via PDO and then change the charset via mysqli, without having a mysqli connection, that is what's causing the warning.
In PDO the charset usually is being specified within the connection string, like this:
$conn = new PDO("mysql:host=yourhost;dbname=yourdbname;charset=utf8");

Unable to connect to database?

This PHP is not working for me, it will not connect
Here is my code
<?php
$server = "localhost";
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";
$mysqlConnection = mysql_connect($server, $username, $password);
if (!$mysqlConnection)
{
echo "Please try later.";
}
else
{
mysql_select_db($database, $mysqlConnection);
}
?>
try this style:sample one and refer this following link
http://php.net/manual/en/function.mysql-connect.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Works fine on my end with my own connection parameters..
You need to change this block to see the exact error...
if (!$mysqlConnection)
{
die(mysql_error());
}
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 !
So nuff said..
Switch to PDO..
<?php
$dsn = 'mysql:dbname=induadmi_db;host=localhost';
$database = "induadmi_db";
$username = "induadmi_main";
$password = "password";
try
{
$dbh = new PDO($dsn, $username, $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();
}

Categories