This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
My code was working but after I inserted a query to check if the first name in MYSQL database already exists, it does not work anymore. Here you can see my code, if you have any tip on how to make this work, I will appreciate it. Thank you very much!
I have tried to work with mysql_num_rows command, but it seems like I didn't use it correctly.
<?php
require_once __DIR__.'/connect.php';
$sName = $_POST['txtName'];
$query = mysql_query("SELECT * FROM users WHERE firstName = '$sName' ");
if (mysql_num_rows ($query) > 0){
echo 'User with this name already exists';
}else{
try {
$stmt = $db->prepare('INSERT INTO users
VALUES (null, :sName, :sLastName, :sEmail, :sCountry )');
$stmt->bindValue(':sName', $sName);
$stmt->execute();
echo 'New user was successfully inserted';
} catch (PDOEXception $ex) {
echo $ex;
}
}
You are trying to use mysql_query when you have (based on the rest of your code that is working) a PDO connection. Change your query to use your existing connection:
try {
$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE firstName = :sName");
$stmt->bindValue(':sName', $sName);
$stmt->execute();
$num_rows = $stmt->fetchColumn();
}
catch (PDOEXception $ex) {
echo $ex;
}
if ($num_rows > 0) {
echo 'User with this name already exists';
}
else {
// the rest of your code here
Related
This question already has answers here:
error in calling same function twice in php
(2 answers)
Closed 2 years ago.
<?php
function insertData()
{
include_once 'database/connection.php';
echo "<br>============= Insert Data =================<br>";
try{
$sql = "INSERT INTO table1 (activity_date, activity_name, activity_point) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $activity_date, $activity_name, $activity_point);
// set parameters and execute
$activity_date = "06-APR-2020";
$activity_name = "Test";
$activity_point = "5";
$res = $stmt->execute();
var_dump("<br>Res:- ".$res);
print_r("<br>Result:- ".$res);
if ($res) {
echo "<br>Id:- ".$conn->insert_id;
echo "<br>New records created successfully";
}
else{
echo "<br>New records not inserted successfully";
}
}
catch(Exception $e){
echo "Exception:- ".$e;
}
finally{
$stmt->close();
$conn->close();
}
}
// insertData();
function selectData()
{
include_once 'database/connection.php';
echo "<br>============= Select Data =================<br>";
try{
$sql = "SELECT * FROM table1 WHERE activity_id > ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $activity_id);
// set parameters and execute
$activity_id = 6;
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$result = $stmt->get_result(); //
$rows = $result->num_rows;
if ($rows > 0){
while ($data = $result->fetch_all())
{
// var_dump($data);
var_export($data);
echo "<br>";
print_r($data);
}
}
else{
echo "Data Not Found";
}
}
catch(Exception $e){
echo "Exception:- ".$e;
}
finally{
$stmt->close();
$conn->close();
}
}
selectData();
?>
The insert function call correctly and data is also inserted correctly.
After inserting I am closing the connection in the finally block.
But at the same time calling selectData() function I got an error.
Undefined variable: conn and Undefined variable: stmt.
How should I reopen the connection for second function?
As you use include_once for your database connection inside the function, this will only load the script the first time. Also at the end of the function you close the connection...
$conn->close();
The second time it calls the function, the include is not done again and the connection is closed, so the connection is not re-made.
You should only create 1 connection for the entire script (rare exceptions may apply). So at the start of your script use the include and then pass the connection to any function/class which need to use it.
include_once 'database/connection.php';
insertData($conn);
Add the parameter to your functions...
function insertData( $conn )
and leave the closing of the connection to the system.
One last thing, which is more my preference is to use require_once or require rather than include_once or include as they will stop the script if the file cannot be found.
In the script in question I'm able to do all that I want to do except prove that an email exists in the database. I know I'm missing something, leaving something out. In this question I'm only showing the code that doesn't work. The rest of the script works. I think the issue is in the if statement, but I just can't seem to figure it out.
if(empty($_POST['email']))
{
$query_email = "
SELECT
email
from users
where
email = :email
";
$query_goes = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query_email);
$result = $stmt->execute($query_goes);
}
catch (PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$row = $stmt->fetch();
if($row)
{
die("This email is already in use...");
}
}
}
Change your code to
if(!empty($_POST['email'])){
//...
}
This way your if statement will be executed, because $_POST['email'] is not empty.
Could be you have forgot the binding
$stmt = $db->prepare($query_email);
$stmt ->bindValue(':email',$_POST['email'], PDO::PARAM_STR);
$result = $stmt->execute();
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 6 years ago.
I have an application that goes by that passes for my PHP a variable (nomecardapioBD and which received and recorded in the variable :nomecardapioBD) which is the table name that I want to select all rows and columns.
But to receive the variable via post can not make the appointment. Can anyone tell me what was wrong with this part of my code ?
$query = "Select * FROM :nomecardapioBD ";
$query_params = array(
':nomecardapioBD' => $_POST['nomecardapioBD']
);
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
Why not this?
$query = "Select * FROM " . $_POST['nomecardapioBD'];
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
You should also do some sort of input sanitization though.
Table and Column names cannot be replaced by parameters in PDO. Just use it as
$table=$_POST['nomecardapioBD'];
$query = "Select * FROM $table";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
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 7 years ago.
Improve this question
I'm totally new to programming (normally I'm a sysadmin) but now I have to do a project where you can register and logon, with PHP and SQLite (there's no alternative).
I need to get a statement where I can do a query:
is there a user with the name from $_POST['username']
with SQLite.
I just don't get it... I found some articles but none of them really helped me.
This is my code:
$db = new PDO('sqlite:mysqlitedb.db');
$sql_create_table_users = 'CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
user_name TEXT,
user_password TEXT
)';
$db->execute($sql_create_table_users);
$username = $_POST['username'];
$sql_checkuserexist = 'SELECT * FROM users WHERE user_name = :user_name';
$stmt = $db->prepare($sql_checkuserexist);
$stmt->execute(array(':user_name'=>$username));
$result = $stmt->fetchAll();
if (count($result) > 0) {
echo 'Exists';
} else {
echo 'Does not exist';
}
But here I get this error:
Fatal error: Call to undefined method SQLite3Stmt::exec()
This error shows to the line where I have
$stmt->execute(array(':user_name'=>$username));
Does anyone know why? My table is called "users" and has got 3 rows: user_id, user_name and user_password.
#Kostas: This is my current code you gave me (I'm only working with this code atm):
try {
//Make your connection handler to your database
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_create_table_users = 'CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
user_name TEXT,
user_password TEXT
)';
$stmt->execute($sql_create_table_users);
$sql = "SELECT * FROM users WHERE user_name = :username";
//Prepared statements so no SQL Injection occurs
$stmt = $db->prepare($sql);
//Execute your query
$stmt->exec(array(':username'=>$_POST['username']));
$result = $stmt->fetchAll();
if (count($result) > 0) {
echo 'Exists';
} else {
echo 'Does not exist';
}
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
You can try the following code. You can find additional info here.
//Make your connection handler to your database
$db = new PDO('sqlite:mysqlitedb.db');
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$username = '';
if (isset($_POST['username'])) {
$username = $_POST['username'];
}
$sql = "SELECT * FROM users WHERE user_name = :username";
$stmt = $db->prepare($sql);
$stmt->execute(array(':username'=>$username));
$result = $stmt->fetchAll();
if (count($result) > 0) {
echo 'Exists';
} else {
echo 'Does not exist';
}
This question already has answers here:
Commands out of sync; you can't run this command now
(23 answers)
Closed 8 years ago.
I am trying to check if row exists. I am getting
Commands out of sync; you can't run this command
I am getting this error because I added $stmt->store_result(); if I remove that line num_rows doesn't return true. How can I check if the row exists?
$title = urldecode($_GET['product-tit/']);
$id = $_GET['item-id-pr'];
$mydb = new mysqli('localhost', 'root', '', 'database');
if(empty($title) || empty($_GET['item-id-pr'])){
header('Location: products.php');
exit();
}
else{
$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $title, $id);
$stmt->execute();
$stmt->store_result();
?>
<div>
<?php
if($stmt->num_rows < 1 ) {
echo "not found";
exit();
} else{
$result = $stmt->get_result();
echo $mydb->error;
while ($row = $result->fetch_assoc()) {
echo wordwrap($row['price'], 15, "<br />\n", true);
exit();
}
$mydb->close ();}}
?>
</div>
It's quite a strange desire of PHP users for the number of rows. Everyone is so eager to get it, while in a web-development there are only a few, extremely rare cases when one is really need it.
Say, here we actually need some data, not number of rows. But using this number only to see if we have any data. Doesn't it look funny/redundant? If we have our data already - why would we need any extra facilities to see if we have it or not?
<?
if(empty($_GET['product-tit']) || empty($_GET['item-id-pr'])){
header('Location: products.php');
exit();
}
$stmt = $mydb->prepare("SELECT * FROM products where title = ? AND id = ? limit 1 ");
$stmt->bind_param('ss', $_GET['product-tit'], $_GET['item-id-pr']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (!$row) { // <---- HERE it is!
echo "not found";
exit();
}
?>
<div>