No database selected? - php

I am trying to insert some values to my database using PDO but it just says "No database selected".
$host = "localhost";
$dbname = "aura";
$user = "root";
$pass = "somepassword";
try {
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$DB->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
$SignUp = $DB->prepare("INSERT INTO `users` (`username`, `password`, `name`, `email`, `rank`, `lvl`, `xp`, `money`, `age`, `reg_ip`, `last_ip`, `created`, `last_online`, `last_action`, `online`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
$SignUp->bindValue(1, $username);
$SignUp->bindValue(2, $password);
$SignUp->bindValue(3, $name);
$SignUp->bindValue(4, $email);
$SignUp->bindValue(5, '1');
$SignUp->bindValue(6, '1');
$SignUp->bindValue(7, '1');
$SignUp->bindValue(8, '100');
$SignUp->bindValue(9, NULL);
$SignUp->bindValue(10, $ip);
$SignUp->bindValue(11, $ip);
$SignUp->bindValue(12, $time);
$SignUp->bindValue(13, $time);
$SignUp->bindValue(14, $time);
$SignUp->bindValue(15, $online);
try{
$SignUp->execute();
} catch(PDOException $e){
die($e->getMessage());
}
I do not know why I get this error because I have connected successfully to the database and as you can see I have specified a database.

It looks ok, but you may have issues with the first try catch and your not killing and possible confusing the insert with the errors from the first.
Also wrap the whole statements in the try catch blocks also using $e->__toString() its going to give you a full stack trace, often that makes it easyier to trace where the error is.
Try this, I couldn't tell you if the following changes will fix the issue but might make it more clearer.
<?php
$host = "127.0.0.1";
$dbname = "aura";
$user = "root";
$pass = "somepassword";
try {
$DB = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass, array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);
} catch(PDOException $e) {
die('<pre>'.$e->__toString().'</pre>');
}
try{
$SignUp = $DB->prepare("
INSERT INTO `users` (`username`, `password`,
`name`, `email`, `rank`,
`lvl`, `xp`, `money`,
`age`, `reg_ip`, `last_ip`,
`created`, `last_online`,
`last_action`, `online`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
$SignUp->bindValue(1, $username);
$SignUp->bindValue(2, $password);
$SignUp->bindValue(3, $name);
$SignUp->bindValue(4, $email);
$SignUp->bindValue(5, '1');
$SignUp->bindValue(6, '1');
$SignUp->bindValue(7, '1');
$SignUp->bindValue(8, '100');
$SignUp->bindValue(9, NULL);
$SignUp->bindValue(10, $ip);
$SignUp->bindValue(11, $ip);
$SignUp->bindValue(12, $time);
$SignUp->bindValue(13, $time);
$SignUp->bindValue(14, $time);
$SignUp->bindValue(15, $online);
$SignUp->execute();
} catch(PDOException $e){
die('<pre>'.$e->__toString().'</pre>');
}
?>

Related

My error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

I got the problem in my blog. When I use single quote in textik this error appear.
INSERT INTO clanky (nadpis, textik, datum, autor, kategorie) VALUES (?, ?, ?, ?, ?);
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 '?, ?, ?, ?, ?)' at line 2
I already know that you cant use single quotes in string due to SQL injection. So im trying to fix it. I tried so many tutorials but nothing helped me.
<?php
if (isset($_POST["btn"])) {
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("ERROR: Could not connect. " . $conn->connect_error);
}
$nadpis = mysqli_real_escape_string($conn, $_POST['nadpis']);
$textik = mysqli_real_escape_string($conn, $_POST['textik']);
$datum = mysqli_real_escape_string($conn, $_POST['datum']);
$autor = mysqli_real_escape_string($conn, $_POST['autor']);
$kategorie = mysqli_real_escape_string($conn, $_POST['kategorie']);
$sql = "INSERT INTO `clanky` (`nadpis`, `textik`, `datum`, `autor`, `kategorie`)
VALUES (?, ?, ?, ?, ?);";
// '". $_POST['nadpis']."','". $_POST['textik']."','". $_POST['datum']."','". $_POST['autor']."','". $_POST['kategorie']."'
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt, "ssiss", $nadpis, $textik, $datum, $autor, $kategorie);
mysqli_stmt_execute($stmt);
}
if (mysqli_query($conn, $sql)) {
echo "New Record added";
header("Location: https://www.globalgraphicdesign.eu/welcome.php");
}else {
echo "Error" . $sql . "" . mysqli_error($conn);
}
$conn->close();
}
?>
I should redirect you to welcome page.
You're trying to prepare it, and using query(), thereby attempting to execute it twice. It will fail when using query(), because placeholders ? are not allowed there. You should also not escape input when using a prepared statement. You should also not output anything before a header() call. You can also enable MySQLi to throw exceptions, which makes error-handling much easier.
Your entire snippet can be reduced to the following.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($servername, $username, $password, $dbname);
if (isset($_POST["btn"])) {
$sql = "INSERT INTO `clanky` (`nadpis`, `textik`, `datum`, `autor`, `kategorie`)
VALUES (?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssss", $_POST['nadpis'], $_POST['textik'], $_POST['datum'], $_POST['autor'], $_POST['kategorie']);
$stmt->execute();
header("Location: https://www.globalgraphicdesign.eu/welcome.php");
$stmt->close();
exit;
}
} catch (Exception $e) {
echo "Something went wrong. Please try again later";
error_log($e->getMessage());
}

Insert is working local but not on server

I use the same Code local and on the server.
While its working just fine local, there is no db-entry while running on the server.
While the INSERT statement is not working i can read and update the rows - so the connection should be fine.
Can somebody help me?
function setDataToParticipantTable($db_host, $db_password, $db_user, $db_name, $new_participant)
{
$db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name, $db_user, $db_password);
$qry = "INSERT INTO " . "`TAEK_Subscriber19`" . " (`Vorname`, `Nachname`, `Email`, `Straße`, `Hausnummer`, `PLZ`, `Ort`, `Land`, `Turnusaerztevertreter`, `DO_VM_WS_1`, `DO_NM_WS_1`, `FR_VM_WS1_1`, `FR_VM_WS2_1`, `FR_NM_WS_1`, `Kongresseroeffnung`, `Kongressparty`, `Infotext`, `Hash`)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$statement = $db->prepare($qry);
$statement->bindParam(1, $new_participant['Vorname']);
$statement->bindParam(2, $new_participant['Nachname']);
$statement->bindParam(3, $new_participant['Email']);
$statement->bindParam(4, $new_participant['Straße']);
$statement->bindParam(5, $new_participant['Hausnummer']);
$statement->bindParam(6, $new_participant['PLZ']);
$statement->bindParam(7, $new_participant['Ort']);
$statement->bindParam(8, $new_participant['Land']);
$statement->bindParam(9, $new_participant['Turnusaerztevertreter']);
$statement->bindParam(10, $new_participant['DO_VM_WS_1']);
$statement->bindParam(11, $new_participant['DO_NM_WS_1']);
$statement->bindParam(12, $new_participant['FR_VM_WS1_1']);
$statement->bindParam(13, $new_participant['FR_VM_WS2_1']);
$statement->bindParam(14, $new_participant['FR_NM_WS_1']);
$statement->bindParam(15, $new_participant['Kongresseroeffnung']);
$statement->bindParam(16, $new_participant['Kongressparty']);
$statement->bindParam(17, $new_participant['Infotext']);
$statement->bindParam(18, $new_participant['Hassh']);
$statement->execute();
$statement = null;
$db = null;
}

Get query back from MYSQLi prepared statement

My prepared statement looks like this:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// prepare and bind
$stmt = $conn->prepare("INSERT INTO `devices` (`deviceName`, `type`, `deviceToken`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $deviceName, $deviceToken, $type);
$stmt->execute();
echo "executed";
$result = $stmt->get_result();
$conn->close();
And I want to echo the query.
I know the PDO method:
$binded_query = $stmt->queryString
But I need to use MYSQLi. So how can I do that?
$sql = "INSERT INTO `devices` (`deviceName`, `type`, `deviceToken`) VALUES (?, ?, ?)"
$stmt = $conn->prepare($sql);
echo $sql; // here you go

Fatal error: Call to a member function bind_param() on a non-object in PHP

I am trying to store data into database from my form.I have try below code,but it will give me fatal error.what is the changes i have to do so that code can work fine.Here i have check my database connection all working fine but there is only one error of fatal error:Call to a member function bind_param() on a non-object.
<?php
if(isset($_POST['submit']))
{
$conn = mysqli_connect('localhost', 'root', '','tmtool');
if($conn -> connect_errno )
{
die('coudn\'t connect to the database' . mysqli_connect_error());
}
if(! get_magic_quotes_gpc() )
{
$Testcase_id = addslashes (filter_input(INPUT_POST, 'Testcase_id'));
$Testcase_title = addslashes (filter_input(INPUT_POST, 'Testcase_title'));
$Testcase_desc = addslashes(filter_input(INPUT_POST, 'Testcase_desc'));
$Product_id= addslashes(filter_input(INPUT_POST, 'Project_id'));
$Date_created= addslashes(filter_input(INPUT_POST, 'Date_created'));
$Created_by= addslashes(filter_input(INPUT_POST, 'Created_by'));
$Type= addslashes(filter_input(INPUT_POST, 'Type'));
$Priority = addslashes(filter_input(INPUT_POST, 'Priority'));
$Precondition= addslashes(filter_input(INPUT_POST, 'Precondition'));
$Test_step = addslashes(filter_input(INPUT_POST, 'Test_step'));
$Expected_result = addslashes(filter_input(INPUT_POST, 'Expected_result'));
$Request_mode = addslashes(filter_input(INPUT_POST, 'Request_mode'));
$Language = addslashes(filter_input(INPUT_POST, 'Language'));
$Category = addslashes(filter_input(INPUT_POST, 'Category'));
$Sub_category = addslashes(filter_input(INPUT_POST, 'Sub_category'));
}
else
{
$Testcase_id =(filter_input(INPUT_POST, 'Testcase_id'));
$Testcase_title =(filter_input(INPUT_POST, 'Testcase_title'));
$Testcase_desc = (filter_input(INPUT_POST, 'Testcase_desc'));
$Product_id=(filter_input(INPUT_POST, 'Project_id'));
$Date_created=(filter_input(INPUT_POST, 'Date_created'));
$Created_by=(filter_input(INPUT_POST, 'Created_by'));
$Type= (filter_input(INPUT_POST, 'Type'));
$Priority =(filter_input(INPUT_POST, 'Priority'));
$Precondition=(filter_input(INPUT_POST, 'Precondition'));
$Test_step =(filter_input(INPUT_POST, 'Test_step'));
$Expected_result =(filter_input(INPUT_POST, 'Expected_result'));
$Request_mode = (filter_input(INPUT_POST, 'Request_mode'));
$Language = (filter_input(INPUT_POST, 'Language'));
$Category = (filter_input(INPUT_POST, 'Category'));
$Sub_category = (filter_input(INPUT_POST, 'Sub_category'));
}
$sql = $conn->prepare("INSERT INTO tmtool.testcase_master ( `Testcase_id`,`Testcase_title`,`Testcase_desc`,`Product_id`,`Date_created`,`Created_by`,`Type`,`Priority`, `Precondition`, `Test_step`, `Expected_result`, `Request_mode`, `Language`, `Category`, `Sub_category`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$sql->bind_param('sssssssssssssss',$Testcase_id,$Testcase_title,$Testcase_desc, $Product_id, $Date_created, $Created_by, $Type , $Priority, $Precondition, $Test_step, $Expected_result, $Request_mode, $Language, $Category , $Sub_category);
if($sql->execute())
{
echo "Entered data successfully\n";
mysqli_close($conn);
}
else {
die('Could not enter data: ' . mysqli_error($conn));
}
}else{
echo "you are not able to connect to data base";
}
?>
You use mysqli_* in OOP style so you have to use the keyword new and remove the _connectpart for the connection like this:
$conn = new mysqli('localhost', 'root', '','tmtool');
//^^^ ^ '_connect' removed
//| See here
Also change your close statement from:
mysqli_close($conn);
to this:
$conn->close();
And for errors you have to use this:
$conn->error //Not mysqli_error($conn)
As suggested by #Rizier123,
When i am try to put prepare statement into if condition then it will work for me...Thanks #Rizier123
Final correction in code is:
if(($sql = $conn->prepare("INSERT INTO tmtool.testcase_master ( `Testcase_id`,`Testcase_title`,`Testcase_desc`,`Product_id`,`Date_created`,`Created_by`,`Subscriber_type`,`Priority`, `Precondition`, `Test_step`, `Expected_result`, `Activation_mode`, `Language`, `Category`, `Sub_category`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))== FALSE)
{
echo "false";
}
$sql->bind_param('sssssssssssssss',$Testcase_id,$Testcase_title,$Testcase_desc, $Product_id, $Date_created, $Created_by, $Subscriber_type , $Priority, $Precondition, $Test_step, $Expected_result, $Activation_mode, $Language, $Category , $Sub_category);

what is wrong with this code

class MyClass {
private $db;
// Constructor
function __construct() {
$this->db = new mysqli('localhost', 'root', 'root', 'Test_db');
$this->db->autocommit(FALSE);
}
// Destructor
function __destruct() {
$this->db->close();
}
// Main method
function MyFun() {
// Check for required parameters
if (isset($_POST["name"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["email"])) {
echo "Before \n";
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$activation = 0;
echo "After \n";
// tracking
$stmt = $this->db->prepare("INSERT INTO users (name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("is", $name, $username, $password, $email, $activation); //Line 95
$stmt->execute();
$stmt->close();
}
Output:
Before
After
Invalid request
MAMP Console:
[15-Apr-2011 15:09:10] PHP Warning: mysqli_stmt::bind_param() [<a href='function.mysqli-stmt-bind-param'>function.mysqli-stmt-bind-param</a>]: Number of elements in type definition string doesn't match number of bind variables in /Applications/MAMP/htdocs/Test/reg.php on line 95
The number is the same but I don't know why this error appears
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
Your "definition" string ("is") contains only two definitions, integer and string ... you should have 5 in there.
$stmt->bind_param("sssss", $name, $username, $password, $email, $activation);
... for example ...
You are only having five ? placeholders in your query, yet you're trying to bing six values to the query.
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
"is"
$name
$username
$password
$email
$activation
The format you are giving does only contain 2 definition, yet it must contain 5 to match your query. Try "sssss".
The "is" is the sixth variable, I suggest you remove this or add the field name in the statement:
$stmt->bind_param("is", $name, $username, $password, $email, $activation);
Either remove from bind_param:
$stmt = $this->db->prepare("INSERT INTO users (name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param($name, $username, $password, $email, $activation);
or add to field names:
$stmt = $this->db->prepare("INSERT INTO users (**is**, name, username, password, email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("**is**", $name, $username, $password, $email, $activation);
or
$stmt = $this->db->prepare("INSERT INTO users (name, username, password,
email,activation) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("issss", $name, $username, $password, $email, $activation);

Categories