I keep trying this code below but for some reason it will not put the value in the database. The table in the database is named 'all'. I get no errors when running the script either.
$user = '0';
$bet = '0';
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name_wd, $db_username, $db_password);
if($pdo){
echo 'works';
}
$query = $pdo->prepare('INSERT INTO all (w_id,w_amt) VALUES (?,?)');
if($query){
echo' works2 ';
}
$query->bindValue(1, $user);
$query->bindValue(2, $bet);
$query->execute();
//echo $user;
echo $user;
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
add ` to your code, because all is a reserved word in mysql
$query = $pdo->prepare('INSERT INTO `all` (`w_id`,`w_amt`) VALUES (?,?)');
And on a side note, if you separated your PDO connection and query, you would have received an SQL syntax error.
Try having seperate functions for PDO connection and querying.
Related
I want to insert 2 tables columns ids to another table
I got the query but there is the annoying error.
I tried to solve this problem for hours none worked :(
This code:
$query = "INSERT INTO
groups(
group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count
)
VALUES(
$group_shcool_id,
$group_teacher_id,
'$group_name',
'$group_note',
'$group_system',
'$group_students_count'
)";
this old:
<?php
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
mysqli_query($con, "SET NAMES 'utf8'");
}
?>
this new:
<?php
// if you are using php just don't forget to add php tags though
$db['db_host'] = "localhost";
$db['db_user'] = "admin";
$db['db_pass'] = "1998";
$db['db_name'] = "ahlquran";
foreach ($db as $key => $value) {
define(strtoupper($key), $value);
}
//using try catch statements
try{
$conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
?>
its connects successfully but all my code use the old one, how to change to convert it? I dont know what pdo I like to learn it, it seems more pro type, but is there solution for this site only using mysqli?
sorry for the long post this is my 1st one, dont know how to explain enough
Thanks
give this error :
QUERY FAILED .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 ' , 'test', '', 'test' at line 11
I thought it will work fine like this but I think the problem with the query syntax.
Just an advice try to use PDO prepared statements example below:
$query = "INSERT INTO groups(group_school_id,
group_teacher_id,
group_name,
group_note,
group_system,
group_students_count)
VALUES (:gsid,:gtid,:gname,:gnote,:gsystem,:gstudcount)";
//assuming $conn is your object variable name for database connection
$stmnt = $conn->prepare($query);
$stmnt->execute(array(':gsid'=>$group_school_id,
':gtid'=>$group_teacher_id,
':gname'=>$group_name,
':gnote'=>$group_note,
':gsystem'=>$group_system,
':gstudcount'=>$group_students_count));
//to check if you have inserted data into your table
$rows = $stmnt->rowCount();
echo "Inserted ".$rows." row";
the :gsid are placeholders for your variables, also make sure that each variable passed are inline with column datatypes in your database
//if you are using php just don't forget to add php tags though
$dbhost = "localhost";
$dbname = "whatevername";
$dbuser = "root";
$dbpass = "";
//using try catch statements
try{
$conn = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully Connected";
}
catch(PDOException $e){
echo "Connection Failed" .$e->getMessage();
}
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
I'm setting to do a simple query using PDO. However, when I run it, it does not insert. The database is called "famous" and the table is called "pessoas" containing only two columns called (codigo and nome).The connection works, but when I execute it return "Error to save".
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;bdname=pessoas';
$user = 'root';
$password = 'init4289';
try{
$pdo = new PDO($dsn, $user, $password);
echo 'SUCESSO AO CONECTAR!';
return $pdo;
}catch(PDOExeption $ex){
echo 'erro: '. $ex->getMessage();
}
}
?>
#end page "conexao_pdo.php"
<?php
include 'conexao_pdo.php';
$conn = getConnection();
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if($stmt->execute()){
echo 'Success to save';
}else{
echo '<p>'.'Error to save';
}
?>
You may consider the following:
probably it's just a typing error - bdname should be dbname in 'mysql:host=localhost;bdname=pessoas'
database and table names - 'famous' and 'pessoas' in the question, 'pessoas' and 'famous' in the code
include exception handling with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
your function getConnection() should return false on failure
Code, based on your question:
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;dbname=pessoas';
$user = 'root';
$password = 'init4289';
try {
$pdo = new PDO(
$dsn,
$user,
$password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
echo 'SUCESSO AO CONECTAR!';
} catch (PDOExeption $ex){
echo 'Error: '. $ex->getMessage();
return false;
}
return $pdo;
}
?>
<?php
include 'conexao_pdo.php';
// Connection
$conn = getConnection();
if ($conn === false) {
exit;
}
// Statement
try
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if ($stmt->execute()) {
echo 'Success to save';
} else {
echo '<p>'.'Error to save';
}
} catch (PDOExeption $ex){
die ('Error: '. $ex->getMessage());
}
?>
I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $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();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim
My goal here is to replicate a local MS Access database into my MySQL database (using php PDO)
The MS Access database is located on a network shared drive and updates itself with new entries every 6 hours.
In the code below I retrieved the max id number from MySQL table 'production_schedule', then I made an ODBC connection to retrieve all entries from MS ACCESS database that are greater than the max id number.
But now I cannot figure out how to insert these new entries into the MySQL table 'production_schedule'.
Can anyone please help?
<?php
/*USING XAMPP*/
$dsn = "mysql:host=localhost;dbname=qmsdb;charset=utf8";
$uname = "root";
$pword = "";
$db = null;
$limit = 10;
$counter = 0;
while (true) {
try {
$db = new PDO($dsn, $uname, $pword);
$db->exec( "SET CHARACTER SET utf8" );
$db->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
$db->setAttribute( PDO::ATTR_PERSISTENT, true );
break;
}
catch (Exception $e) {
$db = null;
$counter++;
if ($counter == $limit)
throw $e;
}
}
$aid = $db->prepare("SELECT MAX(id) FROM production_schedule");
$aid->execute();
$big_id = $aid->fetchColumn();
$refid = intval($big_id);
$conn=odbc_connect('Prod_Schedule','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT * FROM Schedule WHERE ID > $refid";
$rs=odbc_exec($conn,$sql);
if (!$rs) {
exit("Error in SQL");
}
***** INSERT CODE TO PUT THESE MS ACCESS ENTRIES INTO THE MYSQL TABLE ******
?>
something like this maybe:
while(odbc_fetch_row($rs)){
$sql = "INSERT INTO production_schedule (fieldName1, fieldName2, fieldName3) VALUES (?, ?, ?)";
$stmt = $dbh->prepare($sql);
for($i=1;$i<=odbc_num_fields($rs);$i++){
$stmt->bindValue($i, odbc_result($rs,$i));
}
$stmt->execute();
}
Note: depends on how many data you have to dump, you should use a solution like this: PDO Prepared Inserts multiple rows in single query to reduce risk of PHP timeout.
I just tested the following code and it seems to work okay for me:
$dsn = "mysql:host=localhost;port=3307;dbname=myDb;charset=utf8";
$uname = "root";
$pword = "whatever";
$mysqlDb = new PDO($dsn, $uname, $pword);
$mysqlDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$mysqlSql = "INSERT INTO clients (LastName, FirstName) VALUES (?, ?)";
$mysqlCmd = $mysqlDb->prepare($mysqlSql);
$LastName = '';
$FirstName = '';
$mysqlCmd->bindParam(1, $LastName, PDO::PARAM_STR, 255);
$mysqlCmd->bindParam(2, $FirstName, PDO::PARAM_STR, 255);
$connStr =
'Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Public\\Database1.accdb;';
$accessDb = odbc_connect($connStr, "", "");
$accessSql = "SELECT LastName, FirstName FROM Clients";
$accessResult = odbc_exec($accessDb, $accessSql);
while ($accessData = odbc_fetch_array($accessResult)) {
$LastName = $accessData["LastName"];
$FirstName = $accessData["FirstName"];
$mysqlCmd->execute();
}
First create a function to insert the values into MySQL, then loop through the ODBC results;
function createProductionSchedule($company,$person,$order){
$mysqli_con=mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
if (mysqli_connect_errno($mysqli_con))
{
echo 'Failed to connect to MySQL';
}
//Obviously your own fields here
$company = mysqli_real_escape_string($mysqli_con, $company);
$person = mysqli_real_escape_string($mysqli_con, $person);
$order = mysqli_real_escape_string($mysqli_con, $order);
$sql = "INSERT INTO production_schedule VALUES ('$company','$person','$order')";
mysqli_query($mysqli_con, $sql);
return mysqli_insert_id($mysqli_con);
mysqli_close($mysqli_con);
}
Then in your code section
while (odbc_fetch_row($rs))
{
$company=odbc_result($rs,"Company");
$person=odbc_result($rs,"Person");
$order=odbc_result($rs,"Order");
//Call the function to insert the record
createProductionSchedule($company,$person,$order);
}
odbc_close($conn);
I am converting all of my query's to PDO, and i'm new to it.
It's properly a very stupid question but why does the following code not work?
try {
$conn = new PDO('mysql:host=localhost;dbname=ddd', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$id = $_SESSION['id'];
$name = $_POST['name'];
$stmt = $pdo->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
$stmt->execute(array(
':id'=>$id,
':name'=>$name
));
Thanks.
Your connection variable is $conn and you are preparing your PDO Statement using $pdo->prepare.
Change to $conn->prepare()
$stmt = $conn->prepare('INSERT INTO projects
(group_id, project_name)
VALUES (:id, :name)');
You're initializing a variable for your database connection called $conn yet later call $pdo that's not mentioned anywhere. That's the first thing I'd start with.