I'm new to PHP .. I get stuck on how to transfer my sql statement to prepared statement .. The error message that I got is that you " can't connect " ..
My code is as the following
$connection = mysql_connect($host,$username,$password) or die ("can't connect");
$select_database = mysql_select_db($db_name);
$id = mysql_real_escape_string ($_GET ['id']);
$query = 'SELECT * from &tbl_name where id=?';
$stmt = $connection->prepare($query);
$stmt->bind_param("d", $id);
$stmt->execute();
$rows=mysql_fetch_array($stmt);
$stmt->close();
You have two problems actually.
The first, and relevant to your question, is on this line:
$connection = mysql_connect($host,$username,$password) or die ("can't connect");
You say you're receiving the error can't connect. This means that the host, username and/or password for your database connection is invalid. Check that the connection information is correct and you should be able to fix the issue.
The second is that you're connecting to your database with mysql_ functions and then trying to use mysqli_ binding/executing functions. You can't mix and match.
Because you're attempting to bind/execute with OOP style, here's a re-coded sample that should help out:
$connection = new mysqli($host, $username, $password);
if ($connection->connect_error) {
die("can't connect");
}
$query = 'SELECT * from tbl_name where id=?';
$stmt = $connecton->prepare($query);
$stmt->bind_param("d", $id);
$results = $stmt->execute();
$rows = $results->fetch_array();
$stmt->close();
You cannot do prepared statements with the legacy mysql_* set of functions. You need to use PDO or MySQLi:
$dbh = new PDO("mysql:dbname=testdb;host=127.0.0.1", "username", "password");
$query = "SELECT * FROM myTable WHERE id=?";
$stmt = $dbh->prepare($query);
$stmt->execute(array($my_id));
$result = $stmt->fetchAll();
The "can't connect" you have comes from the die() function which will stop execution of your script if mysql_connect fails. This means that your code doesn't succeed creating a connection, check your $host, $username and $password parameters. If your host is remote, make sure that you have the rights to connect to it.
As pce stated, you also have a typo in $connecton which should be $connection
try
1.Define the Database const for later use in your project; (this code should only be executed once)
define( "DBN","foo");//where foo is the database name
define( "DB_USERNAME", "rootuser" ); //generally root
define( "DB_PASSWORD", "my_very_hard_password" ); //be more creative
define( "DB_DSN", "mysql:host=localhost;dbname=".DBN );
...
2.Create PDO Object and execute
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * from &tbl_name where id=:id";
$st = $conn->prepare( $sql );
$st->bindValue( ":id", $obj->id, PDO::PARAM_INT );
// or $st->bindValue( ":id", 5, PDO::PARAM_INT );
$st->execute();
return $st->fetchAll();
Related
I have a query that is working fine in PDO but I am needing to convert the query to MySQLi to be compatible with an older server.
Here is the PDO query:
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM users WHERE username=:username";
$st = $conn->prepare( $sql );
$st->bindValue( ":username", $username, PDO::PARAM_STR );
$st->execute();
while ( $row = $st->fetch() ) {
$db_username = $row['username'];
$db_password = $row['password'];
}
Here is what I have to MySQLi, but it doesn't seem to be working:
$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );
$username = mysqli_real_escape_string($mysqli, $username);
$query = "SELECT * FROM users WHERE username=$username";
if ($result = $mysqli->query($query)) {
while ($obj = $result->fetch_object()) {
$db_username = $obj->username;
$db_password = $obj->password;
}
mysqli_free_result($result);
}
Any help would be very much appreciated :)
Try using the mysqli prepared statement system
$mysqli = new mysqli( 'localhost', DB_USERNAME, DB_PASSWORD, DB_NAME );
$query = "SELECT username, password FROM users WHERE username=?";
$prep = $mysqli->prepare($query);
$prep->bind_param('s', $username);
$prep->execute();
$result = $prep->get_result(); // Make sure you have mysqlnd installed
if($result) {
while ($obj = $result->fetch_object()) {
$db_username = $obj->username;
$db_password = $obj->password;
}
mysqli_free_result($result);
}
If you don't have mysqlnd installed then the less intuitive way involves bind_param
$prep->execute();
$prep->bind_result($db_username, $db_password);
$prep->fetch();
I want to connect to a sql Server.. Only it won't work.
I granted a user and role enough permissions. But what am I doing
<?php
$serverName = "LERAARSKAMER01\SQLEXPRESS";
$database = "sqlservertest";
// Get UID and PWD from application-specific files.
$uid = "sqlAdmin";
$pwd = "tester";
try {
$conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
$query = 'select * from dbo.users';
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row );
}
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
This is a screenshot of the server...
What is wrong?
After searching for a while I found I have to set sql Authentication on.
Microsoft SQL Managment Studio --> Database (right click-> properties->security)
Then I enabled sa, changed the password and settings with this (password policy,...).
It works also with sqlAdmin (the other user). Just with the same code..
USE Master
GO
ALTER LOGIN test_must_change WITH PASSWORD = ‘samepassword’
GO
ALTER LOGIN test_must_change WITH
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;
Can someone explain why this gives me a 500 internal server error? I tried adding some sql injection protection and I'm not sure what I'm doing wrong. Should I be doing this in an object oriented style instead of procedural?
<?php
$conn = mysqli_connect($host, $user, $pwd)or die("Error connecting to database.");
mysqli_select_db($conn, $db) or die("Couldn't select the database.");
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = mysqli_stmt_init($conn);
$query = "SELECT * FROM Users WHERE email=? AND password=?";
mysqli_stmt_prepare($stmt, $query) or die("Failed to prepare statement.");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);
if($count == 1){
//Log in successful
}
else {
//Wrong Username or Password
}
mysqli_close($conn);
?>
mysqli_stmt_get_result is available in PHP 5.3, but I am running 5.1. Also, the mysqlnd driver must be installed for this call to work.
For more information, see Call to undefined method mysqli_stmt::get_result
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 4 months ago.
Obviously, I am preparing the statement wrong, but I am not certain what I am doing wrong.
These 2 code segments are identical, except for the second line.
This fails:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
$sth->setFetchMode(PDO::FETCH_ASSOC);
$res = $sth->fetch();
$dbh = null;
This hard-coded test works:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = 'me#example.com' OR `Users`.`Temp_EMail` = 'me#example.com'");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
$sth->setFetchMode(PDO::FETCH_ASSOC);
$res = $sth->fetch();
$dbh = null;
What am I doing wrong?
Thanks!
UPDATE: Solved!
The exact issue is still unknown, but seems to be related to the 'excessive naming' suggested by user 'Your Common Sense' in the comments below.
This works just fine:
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM Users WHERE EMail=:email OR Temp_EMail=:temp_email");
$sth->execute(array(':email' => $email, ':temp_email' => $email));
Thanks to everyone. I learned lots AND resolved the issue.
Message to Your Common Sense; If you form your comment as an 'Answer', then I can accept it.
It's hard to answer on sight.
Your code seems okay to me. So, debugging seems the only way.
What am I doing wrong?
Always ask this question from your PDO.
Every time you're connecting to PDO, do it this way (also make sure you can see errors, either on-screen or logged):
error_reporting(E_ALL);
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = 'mysql:host=localhost;dbname=' . $DB_Database;
$dbh = new PDO($dsn, $DB_UserName, $DB_Password, $opt);
if there is an error - you'll be notified.
If there isn't - check typo-like problems.
Just a quick try - Do you get it right with these two lines ?
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->execute(array(':email' => 'me#example.com', ':temp_email' => 'me#example.com'));
in other words... Did you set your $email variable ?
try this
$dbh = new PDO('mysql:host=localhost;dbname=' . $DB_Database, $DB_UserName, $DB_Password);
$sth = $dbh->prepare("SELECT * FROM `PNB`.`Users` WHERE `Users`.`EMail` = :email OR `Users`.`Temp_EMail` = :temp_email");
$sth->bindParam(':email', $email, PDO::PARAM_STR);
$sth->bindParam(':temp_email', $email, PDO::PARAM_STR);
$sth->execute();
$res = $sth->fetch(PDO::FETCH_ASSOC);
$dbh = null;
In the past I've had no issues using one simple:
$link = db_connect();
in a single file with multiple SQL commands like so:
$sql = "UPDATE table SET...";
$sql_result = mysql_query($sql, $link)
or die("Couldn't execute query.");
$sql2 = "UPDATE table2 SET...";
$sql_result2 = mysql_query($sql2, $link)
or die("Couldn't execute query.");
Now any new file I create won't work without multiple/separate db_connects. For example:
$link = db_connect();
$link2 = db_connect();
$sql = "UPDATE table SET...";
$sql_result = mysql_query($sql, $link)
or die("Couldn't execute query.");
$sql2 = "UPDATE table2 SET...";
$sql_result2 = mysql_query($sql2, $link2)
or die("Couldn't execute query.");
The old files with multiple mysql_queries referencing a single db_connect(); are still working fine. What could have changed?
Thanks.
Updated to include the db_connect(); function:
function db_connect($db="database", $host="localhost", $user="user", $p="password") {
$dbcnx = #mysql_connect($host, $user, $p);
if (!$dbcnx)
{
echo( "<p>Unable to connect to the database server at this time.</p>" );
exit();
}
$database = #mysql_select_db($db, $dbcnx);
if (!$db)
{
echo "<p>Unable to locate the database at this time.</p>";
exit();
}
return $dbcnx;
}
If you want to have $links separated, add true as fourth mysql_connect() parameter:
$dbcnx = #mysql_connect($host, $user, $p, true);
Additionally if you want to use different connections (different databases, users, passwords), you need to explicitly pass parameters to db_connect() second time:
$link2 = db_connect('database2', 'whateverthehost', 'user2', 'andhispassword');
What you have posted looks fine unless you have something unset() ing $link, assigning it a value, or something else that is making $link no longer pointing to the database.