Can anyone tell me about how to build a connection between mysql and php page.
Please help me with this.
To start a connection You Might do Following code:-
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
//change test with your server details//
$conn = mysqli_connect($servername,$username,$password,$dbname);
if ($conn)
{
//echo "connection ok";
}
else
{
echo "connection Failed";
}
?>
hope this code would help you .
Make conn.php file with this code inside and use $conn variable to prepare queries using prepared statement
if(!defined("connection")){
header('Location:error.php');
exit();
}
define("host","localhost");
define("user","mysql_user");
define("pass","password");
define("dbname","database_name");
$conn=new mysqli(host,user,pass,dbname);
if($conn->connect_error){
die("Failed to connect");
exit();
}
mysqli_set_charset($conn,"utf8mb4");
Use conn.php and $conn variable like this
Page.php
require_once("conn.php");
if($stmt = $conn->prepare($query)){
echo "prepared";
}
Related
I'm struggling with the following problem. Some years ago, I've written a function to retrieve MYSQL results (multiple rows). Till PHP7, this code worked fine:
function MultipleRows($query)
{
global $dbhost, $dbname, $dbuser, $dbpass;
mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error! Couldn't <b>Connect</b>.");
mysql_select_db($dbname)
or die("Error! Couldn't <b>Select database</b>.");
$result = mysql_query($query)
or die("Error! Couldn't execute query.");
if(($result)&&(mysql_num_rows($result)>0))
{
return $result;
} else {
return false;
}
mysql_close();
}
Now in PHP7, this code doesn't seem to work anymore. After a lot of searching I came up with this as a replacement but unfortunately it doesn't work:
function MultipleRows($query)
{
$mysqli = new mysqli($dbhost, $dbpass, $dbuser, $dbname);
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
return $result;
$mysqli->close();
}
The function is meant to work with code like this:
$res_test = MultipleRows("SELECT id, name FROM table");
if($res_test)
{
while($res = mysql_fetch_array($res_test))
{
echo $res['id'].' '.$res['name'];
}
}
It's not a good option to rewrite the 'display code' (last fragment) because in that case I have to rewrite many lines in my website. Who can give me some help in this? Thanks in advance!
mysql extension has been dropped from PHP 7, after being deprecated in PHP 5.x.
You could rewrite function MultipleRows() using mysqli as follows:
function MultipleRows($query)
{
global $dbhost, $dbpass, $dbuser, $dbname;
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result = $mysqli->query($query);
if ($result !== FALSE)
$result = $result->fetch_all(MYSQLI_ASSOC);
$mysqli->close();
return $result;
}
A few remarks:
it is not a good idea to use global variables ($dbhost, $dbuser, $dbpass and $dbname)
this way of handling database queries makes you vulnerable to SQL injection attacks
Hello since yesterday i am trying to get the transaction hash on blockchain send many api and send to mysql but it dont works. i put to insert at mysql $txid but it give wrong results as per example "2147483647" i really thanks for any help. Below is my code.
<p>$guid="***********";
$firstpassword="**********";
$secondpassword="**************";
$amounta="3599";
$amountb="2000";
$amountc="2000";
$addressa="********";
$addressb="***********";
$addressc="******";
$recipients=urlencode('{
"'.$addressa.'": '.$amounta.',
"'.$addressb.'": '.$amountb.',
"'.$addressc.'": '.$amountc.'
}');
$json_url =
"https://blockchain.info/pt/merchant/$guid/sendmany?password=******&second_password=********&recipients=$recipients¬e=********";
$json_data = file_get_contents($json_url);
$json_feed = json_decode($json_data);
$message = $json_feed->message;
$txid = $json_feed->tx_hash;
$tx = "$txid";
$servername = "localhost";
$username = "******";
$password = "*******";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$<font color="#FF0000">sql = "INSERT INTO payments (user_id, transaction_hash,
payment, date)
VALUES ('5331', '$txid', '4', now())";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;<br>
}
$conn->close();
?>
Lol, sorry that scrypt work very well, the problem i a set the table as INT 11, so i changed it to vachar 255 and its works well.
Thanks
I have to change an old mysql to PDO, I am working with a code its made by someone else, so I have this following code to change in PDO
The original code is
function liste($a,$b,$c)
{
$queryliste= "SELECT id,nom,prenom
FROM table";
$this->list = Connection_Base($querylistactu);
}
//Connection_Base
function Connection_Base($query)
{
$link = mysql_connect(DATABASESERVER, DATABASEUSER, DATABASEPASSWORD);
$ret = mysql_select_db(DATABASEDB, $link);
if (!$ret)
{
die("Echec de connection");
} else {
$mysql_desc = DATABASEDB;
if(!$result = mysql_query( $query))
{
return 0;
} else {
return $result;
}
mysql_close($link);
}
}
This is the part with which I have problem. I want to change it using PDO.
while( list($x,$y,$z) = mysql_fetch_row($lactu->list) )
I am proceed like this but it doesn't work
while( list($x,$y,$z) = $lactu->list->fetch(PDO::FETCH_NUM)
any ideas ?
Why don't you use PDO::FETCH_ASSOC? Check the code sample for connecting to database, executing the query, fetching all rows and iterate over the rows.
//Your query
$queryliste = "SELECT id, nom, prenom FROM table";
//Initialize pdo connection use your $name, $host, $username and $password
$pdoLink = new PDO("mysql:dbname={$name};host={$host};charset=utf8", $username, $password);
//Prepare statement
$statement = $pdoLink-> prepare($queryliste);
//Execute query
$statement -> execute();
//(1) Fetch rows using PDO::FETCH_ASSOC
$rows = $statement -> fetchAll(PDO::FETCH_ASSOC);
$statement -> closeCursor();
foreach($rows as $row) {
echo $row['id'];
echo $row['nom'];
echo $row['prenom'];
}
//(2) or you can use PDO::FETCH_NUM
$rows = $statement -> fetchAll(PDO::FETCH_NUM);
$statement -> closeCursor();
foreach($rows as list($x, $y, $z)) {
echo $x;
echo $y;
echo $z;
}
//(3) or you can rewrite the last in the same form you are using as
while((list($x, $y, $z) = $statement->fetch(PDO::FETCH_NUM))) {
echo $x;
echo $y;
echo $z;
}
$statement -> closeCursor();
I am trying to call a record from a table into html to create an admin page so the content can be updated. I cannot get the record to come up. I am totally new to this so any help is appreciated. My table name is tblContent and my database name is data1. I have only one row in the table with a PageID of 1.
home.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php echo mysql_result($rs,0,”PageTitle”);?></title>
<link rel="stylesheet" type="text/css" href="origstyle.css">
</head>
<body>
<div id="container">
<h1>Site Heading</h1>
<?php
require_once 'classes.php';
try {
$conn = new PDO("mysql:host=$host;db_name=$db_name", $db_username, $db_password);
$rs = mysql_query("getData");
echo mysql_result($rs,0,”Content”);
} catch (PDOException $pe) {
die("Could not connect to the database $db_name :" . $pe->getMessage());
}
?>
</div>
</body>
</html>
classes.php
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'XXXXdbName'; //Database Name
$db_username = 'XXXXuserName'; //Database Username
$db_password = 'XXXXpass'; //Database Password
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
class database
{
function __construct($pdo)
{
$this->pdo = $pdo;
}
function getData()
{
$query = $this->pdo->prepare('SELECT * FROM data1');
$query->execute();
return $query->fetchAll();
}
}
?>
There's quite a lot of little issues that stop this code from working.
The biggest is that you are trying to use two different database libraries. There's the deprecated mysql library which has all the functions starting with mysql_ and then there's PDO. Replace all the mysql functions with their PDO counterparts.
The next thing I notice is that you seem to be thinking that you pass a method name to the querying function (mysql_query"myData"), but you do not. You call the method on an instance of the class. First you create an instance, like you did for the PDO object, and then you call a method.
$database = new database()
$rs = $database->getData()
The third thing I noticed is that you are creating the PDO object twice. There's no need to create the instance in home.php, so just get rid of that (along with the try/catch stuff related to it).
The fourth thing is minor. You should also capitalize your class names.
Put these together, and you get something like this:
home.php:
require_once "classes.php";
$rs = $database->getData();
// Code that turns $rs into HTML
// Sorry, I don't know PDO well enough to
// say what that is.
// I do know that a simple echo will not suffice.
classes.php:
$host = "localhost"
$db_name = "";
$db_username = "";
$db_password = "";
class Database {
function __construct($pdo) {
$this->pdo = $pdo;
}
function getData () {
$query = $this->pdo->prepare('SELECT * FROM data1');
$query->execute();
return $query->fetchAll();
}
}
try {
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
} catch (PDOException e) {
exit('Error Connecting To DataBase');
}
$database = new Database($pdo);
I have ci installed on a regular MAMP stack, and I’m working on this tutorial. However, I have only gone through the Created section, and currently I am getting a No database selected error.
Model:
<?php
class submit_model extends Model {
function submitForm($school, $district) {
$data = array(
'school' => $school,
'district' => $district
);
$this->db->insert('your_stats', $data);
}
}
View:
<?php $this->load->helper('form'); ?>
<?php echo form_open('main'); ?>
<p>
<?php echo form_input('school'); ?>
</p>
<p>
<?php echo form_input('district'); ?>
</p>
<p>
<?php echo form_submit('submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
Controller:
<?php
class Main extends controller {
function index() {
// Check if form is submitted
if ($this->input->post('submit')) {
$school = $this->input->xss_clean($this->input->post('school'));
$district = $this->input->xss_clean($this->input->post('district'));
$this->load->model('submit_model');
// Add the post
$this->submit_model->submitForm($school, $district);
}
$this->load->view('main_view');
}
}
database.php
$db['default']['hostname'] = "localhost:8889";
$db['default']['username'] = "root";
$db['default']['password'] = "root";
$db['default']['database'] = "stats_test";
$db['default']['dbdriver'] = "mysql";
$db['default']['dbprefix'] = "";
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = "";
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_general_ci";
config.php
$config['base_url'] = "http://localhost:8888/ci/";
...
$config['index_page'] = "index.php";
...
$config['uri_protocol'] = "AUTO";
So, how come it’s giving me this error message?
A Database Error Occurred
Error Number: 1046
No database selected
INSERT INTO `your_stats` (`school`, `district`) VALUES ('TJHSST', 'FairFax')
Try leaving your password blank.
I think that's the default for WAMP and XAMPP. It could be for MAMP as well.
I assume you are (auto)loading the database class?
double check this, and also check the database name is correct.