I'm trying to create a system, where my website generates an unique code (current date + 5 random characters) and that code is transferred to a table in my database.
Before function generateNumber() can insert the unique code into the database, it has to check if the code already exist in the database.
If the code doesn't exist, my function works flawlessly. But the problem is when the code can already be found on the database, my website just doesn't do anything (it should just re-run the function).
function generateNumber()
{
global $conn;
$rand = strtoupper(substr(uniqid(sha1(time())),0,5));
$result = date("Ydm") . $rand;
$SQL = $conn->query("SELECT code FROM test WHERE code='$result'");
$c = $SQL->fetch(PDO::FETCH_ASSOC);
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
} else {
$sql2 = "INSERT INTO test (code) VALUES (?)";
$stmt2 = $conn->prepare($sql2);
$stmt2->execute([$result]);
return $result;
}
}
try {
$conn = new PDO("sqlite:db"/*, $username, $password*/);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo generateNumber();
}
catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$conn = null;
?>
There are no error messages in the console, but I suspect the problem is this part of the code:
if ($c['code'] > 0) { // test if $result is already in the database
generateNumber();
}
Any idea how I can write this function in a better way?
Solution :
if ($c['code'] > 0) { // test if $result is already in the database
// if the code exists in db the function return nothing
// because you are missing a return :
return generateNumber();
}
Related
Good day!
I am working on building a dummy application form that inserts data to a mySQL database. When running the functions, I successfully insert the data into the database. However, when the functions worked successfully, I am getting an error SQLSTATE[HY000]: General error
I thought it was occurring within my database access function, but it seems to be connecting alright. Here is my db access function:
function connectToDB($params)
{
try
{
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare($params['sql']);
$stmt->execute($params['bindParam']);
$results = array();
$results['rowCount'] = $stmt->rowCount();
if($results['rowCount'] == 1)
{
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] < 2) {
$results = $stmt->fetch(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] > 2) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
} elseif($results['rowCount'] == 2) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $params;
}
Is there something I am missing in my code or is there something that shouldn't be in my db access code? I hope to learn from this to apply it in the future while I'm still trying to learn/improve on my PHP along the way. I hope I did my best to explain my issue and I appreciate your time reading!
Thank you
You do not use fetchAll().
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
with insert queries. Removing this statement it should fix your problem. Remember every fetch and fetchAll from your code.
Hei,
I need a function in php that checks if a value entered by form is already in database (sql - server -- PDO), and return TRUE or FALSE.
I tried to do this, but I got stuck and didn't found a solution on internet.
could you give me a hint on how to threat the above condition ?
function check_code($code) {
GLOBAL $handler;
$code = check_input($code);
try{
$query2 = $handler -> prepare("SELECT code from stock where code = :code");
$query2 -> execute(array(
':code' => $code
));
return >???<
}
catch(PDOException $e){
echo $e -> getMessage();
} }
return something like row_count(result) > 0
I've never work with sql-server before but I had worked with PDO many times, basically this is how would check in pdo
<?php
function check_code($code)
{
GLOBAL $handler;
$code = check_input($code);
try {
$query2 = $handler->prepare("SELECT code from stock where code = :code");
$query2->execute(array(':code' => $code));
$results = $query2->fetchColumn();
if (count($results) > 0) {
echo "exists";
} else {
echo "does not exist";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
NB: Avoid using the Global var... Stop using `global` in PHP
So I am grabbing the amount of rows in a specific table where the username is already in the database like so:
$second_sql = $db->prepare("SELECT * FROM users WHERE username = :username");
$second_sql->bindParam(':username', $username);
$second_sql->execute();
if($second_sql->rowCount() == 1) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
The problem is it's not working. If you need more of the script just tell me.
Some databases does not report the row count with PDO->rowCount() method.
SQLite, for instance.
So don't use rowCount(); doing so makes your code less portable.
Instead use the COUNT(*) function in your query, and store the result in a variable.
Finally, use that variable to fetch the one and only column (users) using the fetchColumn() method.
So you can play with this:
try {
$second_sql = $db->prepare("SELECT COUNT(*) from users WHERE username = :username");
$second_sql->bindParam(':username', $username, PDO::PARAM_STR);
$second_sql->execute();
$count = $second_sql->fetchColumn();
} catch (PDOException $e) {
// Here you can log your error
// or send an email
// Never echo this exception on production
// Only on development fase
echo "Error: " . $e->getMessage();
}
if ($count) {
$db = null;
header("Location: ../login/");
} else {
$statement->execute();
$db = null;
}
Perhaps you wanna test you condition for a single row:
if ($count == 1)
Hope this helps you.
Cheers!
When I run this query SELECT COUNT(ID) FROM blog_posts in PHPmyadmin it returns the number of rows in my database which is what I want but now I want this number to be displayed on my success.php page using the count method below.
Heres my code so far:
Database.class.php
<?php
include 'config/config.php'; // Inlude the config file, this is where the database login info is stored in an array
class database {
private $dbc; // Define a variable for the database connection, it's visabiliatly is set to 'private' so only this class can access it
function __construct($dbConnection){
// Running the __construct() magic function,
// I am passing through a variable into the contruct method which when the object is created will hold the login details from the $dsn array in config.php
$this->dbc = $dbConnection; // This is saying that the variable $dbc now has the same value as $dbConnection ($dsn array)
$this->dbc = mysqli_connect($this->dbc['host'], $this->dbc['username'], $this->dbc['password'], $this->dbc['database']);
// ^ Running the mysqli_connect function to connect to the database.
if(mysqli_connect_errno()){ // If there is a problem connecting it will throw and error
die("Database connection failed" . mysqli_connect_error());
} else {
echo "allgood";
}
}
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
}
function count($countSQL){ // This is the method used for counting
mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
}
}
?>
Success.php
<?php
include 'classes/database.class.php';
include 'config/config.php';
echo '<h2>Success page</h2>';
$objdb = new database($dsn);
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$objdb->insert($insertSQL);
$countSQL = "SELECT COUNT(ID) FROM blog_posts";
$objdb->count($countSQL); // Executes the query, now how do I display the result? I have tried 'echo'ing this but it doesn't seem to work
?>
Actually its much better to add an alias in your query:
$countSQL = "SELECT COUNT(ID) as total FROM blog_posts";
$result = $objdb->count($countSQL);
echo $result['total'];
Then, on your methods:
function count($countSQL){ // This is the method used for counting
$query = mysqli_query($this->dbc, $countSQL);
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $countSQL" . $this->dbc->error);
}
$result = $query->fetch_assoc();
return $result;
}
Additional Info:
It might be good also on your other methods to put a return value. So that you'll know that it worked properly.
Example:
function insert($insertSQL){ // Creating an insert function and passing the $insertSQL variable into it
$query = mysqli_query($this->dbc, $insertSQL); // Querying the database and running the query that is located in 'success.php'.
if (mysqli_connect_errno($this->dbc)) { // Will throw an error if there is a problem
die("Failed query: $insertSQL" . $this->dbc->error);
}
return $this->dbc->affected_rows;
}
So that here:
$insertSQL = "INSERT INTO blog_posts VALUES(NULL, 'Test', 'THis is a message')";
$insert = $objdb->insert($insertSQL); // so that its easy to test if it indeed inserted
if($insert > 0) {
// hooray! inserted!
}
Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"