how can i resolve my problem with sql request in php [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have a problem with my sql request in my php. I try to use the "query" but when I do a "fetch" I get an error. I know this error is because of my sql request but I can't find the problem.
my php code :
$host = 'localhost';
$dbName = 'appliderencontre';
$username = 'root';
$pswd = '';
try
{
$db = new PDO("mysql:host=" .$host .";dbName=" . $dbName, $username, $pswd);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e;
}
$requete = "SELECT pseudo FROM user";
$reponse = $db-> query($requete);
while($donnee = $reponse->fetch()){
echo $donnee['pseudo'];
}
$reponse ->closeCursor();
And that is my error :
I need your help, i can't find anything for helping me.
Thanks a lot !
(Sorry for my english, i'm a begginer).

Change this code :
$db = new PDO("mysql:host=" .$host .";dbName=" . $dbName, $username, $pswd);
to
$db = new PDO("mysql:host=" .$host .";dbname=" . $dbName, $username, $pswd);
because dbname must be lower-case.

Try to run this code and use PDO::FETCH_OBJ in the fetch function.
$host = "localhost";
$user = "root";
$password = '';
$dbname = "appliderencontre";
try {
$dns = "mysql:host=".$host.";dbname=".$dbname.";charset=utf8";
$pdo = new PDO($dns, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "PDOError: " . $e->getMessage()." In ".__FILE__;
}
$query = 'SELECT pseudo FROM user';
$query = $pdo->query($query);
while ($row = $query->fetch(PDO::FETCH_OBJ)) {
echo $row->pseudo;
echo '<br>';
}

Related

i want get data from table sql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i have a table register with email and username colums.
> ex - username email
> test test#gmail.com
> new new#gmail.com
SELECT * FROM Register WHERE email='test#gmail.com'
I can get this colom ,but i cant select username.i want assign username to variable
I think you want something like this if you use MySQL :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT username, email FROM MyTable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "username: " . $row["username"]. " - email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
In my opinion you're probably a beginner with web development with databases.
I recommend you w3chools. You can reed various examples in this site:
https://www.w3schools.com/php/php_mysql_select.asp
Your question is not clear, but if you are new with database I recommend you to start with PDO instead of mysqli.
<?php
//Db connection
function pdo_connect_mysql() {
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phpcrud';
try {
return new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
} catch (PDOException $exception) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to database!');
}
}
// User Input
$username = 'john';
$email = 'john#gmail.com';
$sql = 'SELECT * FROM register WHERE username = ? email = ?';
$stmt = pdo_connect_mysql() ->prepare($sql);
$stmt->execute([$username, $email]);
$register = $stmt->fetchAll();
?>

I can't view the database content on a php page [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I can't view the database content on php page
I want to fetch data using ID
thats the code :
<?php
//connect with database
$servername = "localhost";
$userdbname = "root";
$dbpassword = "";
$dbname = "users";
$usid = 0;
$docname = '';
$conn = new mysqli($servername, $userdbname, $dbpassword, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users WHERE id=".$usid;
if ($conn->query($sql) === TRUE) {
$conn->close();
$URLS = array();
while ($row = $result->fetch_array()) {
$docname= $row['docname'];
}
header("Location:Editeform.php");
}
?>
This is the form I am trying to view the data in :
<div class="form-group">
<input type="text" class="form-input" name="docname" id="name" placeholder="Your Name" value="<?php echo $users['docname']; ?>" />
</div>
I have made an example how it could look with PDO (as i see you are just starting and i suggest to learn PDO as its not that hard)
This way you also are safe from SQL injections.
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$usid = 0;
$docname = '';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
$stmt = $pdo->query("SELECT * FROM users WHERE id=?");
$stmt->execute([$usid]);
$row = $stmt->fetch();
$docname = $row['docname'];
echo '
<div class="form-group">
<input type="text" class="form-input" name="docname" id="name" placeholder="Your Name" value="'.$docname.'" />
</div>';
P.S. I have not tested it so fill your details and give it a try!
Here is really good website to learn all about PDO: https://phpdelusions.net/pdo

PHP OOP MySQL connection [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In previous projects, I use the following code to connect to MySQL database:
File: connect.php
define('DB_SERVER','my_server');
define('DB_DATABASE','my_database');
define('DB_SERVER_USERNAME','my_user');
define('DB_SERVER_PASSWORD','my_password');
$db_server = DB_SERVER;
$db_username = DB_SERVER_USERNAME;
$db_password = DB_SERVER_PASSWORD;
$db_database = DB_DATABASE;
$connection = mysqli_connect($db_server, $db_username, $db_password,$db_database);
if ($connection) {
//Connected OK
} else {
die ("Cannot connect to database $db_database in $db_server!");
}
And all my other scripts looks like the next:
include "connect.php"
//From here, I can use the $connection variable to select/insert/delete/update data in my_database.
Now, I'm trying to use a more OOP approach in my programming, then I create the next code to connect to MySQL:
Class Connection extends mysqli{
public function __construct(){
if ($config = parse_ini_file('config/config.ini',true)){
$server = $config['database']['server'];
$username = $config['database']['username'];
$password = $config['database']['password'];
$database = $config['database']['dbname'];
parent::__construct($server,$username,$password,$database);
if (mysqli_connect_error()){
$message = "Conection error (" . mysqli_connect_errno() . ") " .
mysqli_connect_error();
throw new Exception($message);
}
} else {
$message = "Config file not found.";
throw new Exception($message);
}
}
}
And my scripts now looks like:
set_include_path(__DIR__.'/Classes');
spl_autoload_extensions(".php");
spl_autoload_register();
try {
$connection = new Connection();
} catch (Exception $ex){
die($ex->getMessage());
}
//Again, from here I can use the variable $connection to use my database
Both solutions works, but...
The questions are:
Is this necessary or am I overcomplicating these scripts?
Are there best practices in this concerns?
Thanks in advance for any comments to improve all of this.
config.php:
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'databasename'; //Database Name
$db_username = 'root'; //Database Username
$db_password = ''; //Database Password
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
?>
database.class.php:
<?php
class database
{
function __construct($pdo)
{
$this->pdo = $pdo;
}
function getData()
{
$query = $this->pdo->prepare('SELECT * FROM database');
$query->execute();
return $query->fetchAll();
}
}
?>
index.php:
<?php
require_once 'config.php';
require_once 'database.class.php';
$db = new database($pdo);
$rows = $db->getData();
?>

Fetching PDO - $handler vs $stmt?

I am VERY new to PHP / PDO, so please be gentle...
I am trying to enter code into my database and then fetch it into a webpage. I am able to do the first but am having difficulty displaying it. I am wondering if it's because i'm trying to combine $stmt and $handler together?
This is my code for entering the information into the database:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO survey (storename, receipt, date_visit)
VALUES (:storename, :receipt, :date_visit)");
$stmt->bindParam(':storename', $storename);
$stmt->bindParam(':receipt', $receipt);
$stmt->bindParam(':date_visit', $date_visit);
// insert a row
$storename = $_POST['storename'];
$receipt = $_POST['receipt'];
$date_visit = $_POST['date_visit'];
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
It works perfectly.
This is my code for fetching information from my database.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$handler->setAttribute(PDO::ATRR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class SurveyEntry {
public $id, $storename, $receipt, $date_visited,
$entry;
public function __construct() {
$this->entry = "{$this->storename} posted: {$this->receipt}";
}
}
$query = $handler->query('SELECT * FROM survey');
$query->setFetchMode(PDO::FETCH_CLASS, 'SurveyEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
I can confirm that it connects correctly, but I can't get it to display any information. I'm wondering if it's something to do with the difference in $stmt and $handler that i'm using? I've been following tutorials online and have quite possibly mixed 2 tutorials together to try and achieve what i'm looking for.
UPDATE:
I managed to get it to work by updating how I called from the database:
$host = "localhost";
$dbname = "test";
$user = "test";
$password = "test";
$handler = new PDO( "mysql:dbname=$dbname;host=$host" , $user , $password );
Figured it out - I had 'ATRR_ERRMODE' instead of 'ATTR_ERRMODE' (typo)
how are you?
You should try to fix it:
1- Two different connections:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');

Can't connect on database on my localhost [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I have php script:
<?php
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$con = mysql_connect($host, $username, $pass);
if (!$con) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
running on remote server and when I execute it and try to connect to database located on my PC i get an error:
Warning: mysql_connect() [function.mysql-connect]: Can't connect to MySQL server on '109.60.110.255' (4) in /home/a6859995/public_html/zavrsni/connect.php on line 12
How can I fix that?
I recommend to use pdo like this:
class_config.php:
class class_config {
public static $db_host = 'localhost';
public static $db_name = 'yourdbname';
public static $db_user = 'youruser';
public static $db_pass = 'yourpass';
}
class_pdo.php:
require_once "class_config.php";
class class_pdo {
public static function dbFactory() {
$host = class_config::$db_host;
if(strpos($host,":") !==false) {
$parts = explode(":",$host);
$hostname = "unix_socket=".$parts[1];
} else {
$hostname = "host=$host";
}
$user = class_config::$db_user;
$pass = class_config::$db_pass;
$dbase = class_config::$db_name;
$pdo = new PDO("mysql:$hostname;dbname=$dbase", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $pdo;
}
}
use it in your script like this:
require_once("class_pdo.php");
$pdo = class_pdo::dbFactory();
$stmt = $pdo->prepare("SELECT * FROM `tablename` WHERE id = :id ");
$stmt->bindValue(":id", $id, PDO::PARAM_INT);
$stmt->execute();
[...]
Try This instead: mysql_connect() is deprecated so use mysqli_connect...
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$databae = $_GET['database'];
$con = mysqli_connect($host, $username, $pass, $database);
if (mysqli_connect_errno()) {
echo 'Connection failed!';
} else {
echo 'Connected successfully!';
}
mysql_close($con);
?>
Though mysql_connect() is deprecated try using PDO.. I am just presenting it in mysql_connect for you..
$host = $_GET['host'];
$username = $_GET['username'];
$pass = $_GET['pass'];
$database = $_GET['database'];
$connect=new connect($host,$username,$pass,$database);
class connect{
function __construct($host,$user,$password,$db_name){
mysql_connect($host,$user,$password) or die("Connection error");
mysql_select_db($db_name);
$error=mysql_error();
if (!empty($error))
{
echo $error;
}
}
}
Thanks everyone on help. Main problem were privileges on MySQL database, but PDO usage helped me to understand how it's to be done these days, sorry on n00b code at start :D

Categories