I am trying to write a serial and random PIN to mysql database but some PIN values are written multiple times.
how do I skip writing $pin into pin column if it already exist?
The snippet follows:
<?php
for($serial = 1000; $serial <= 1600; $serial++) {
$serial_prefix = "HCIS";
//generate random figures.
$rand_pin1 = rand(10599, 99999);
$rand_pin2 = rand(22222, 89898);
$pin = $rand_pin1 . $rand_pin2;
$f_serial = $serial_prefix . $serial;
$check = "SELECT pin FROM pin_serial WHERE pin = '$pin'";
$check_query = mysqli_query($connection, $check);
if(mysqli_num_rows($check_query) > 0){
// how do I skip writing $pin into pin column if it already exist here
}
elseif(mysqli_num_rows($check_query) == 0){
//inserting a generated figure and $serial into serial and pin column.
$pin_serial_query = "INSERT INTO pin_serial (serial, pin) VALUES('$f_serial', '$pin')";
mysqli_query($connection, $pin_serial_query);
}
}
Create unique index for pin column:
ALTER TABLE `pin_serial` ADD UNIQUE INDEX (`pin`)
Then change your query to
INSERT INTO pin_serial (serial, pin) VALUES('$f_serial', '$pin')
ON DUPLICATE KEY UPDATE serial_pin = VALUES(serial_pin)
(note ON DUPLICATE KEY UPDATE serial_pin = VALUES(serial_pin) part, this is just example, you can just pin=pin to skip) It will update query if row with that pin value already exists, or insert a new row.
You also can use INSERT IGNORE statement, which will just ignore duplicates.
More about INSERT in MySQL docs on topic
Please note that in your example, the script is vulnerable to Sql injection attack. To avoid it, you should first pass your parameters to mysqli_real_escape_string function to make the data inside sql-safe(by escaping ambiguous characters)
A do..while loop should solve your problem:
for ( $serial = 1000; $serial <= 1600; $serial++ ) {
$serial_prefix = "HCIS";
do {
// generate random figures
$rand_pin1 = rand( 10599, 99999 );
$rand_pin2 = rand( 22222, 89898 );
$pin = $rand_pin1 . $rand_pin2;
$f_serial = $serial_prefix . $pin;
$check = "SELECT pin FROM pin_serial WHERE pin = '$pin'";
$check_query = mysqli_query( $connection, $check );
} while ( mysqli_num_rows( $check_query ) >0 );
//inserting a generated figure and $serial into serial and pin column.
$pin_serial_query = "INSERT INTO pin_serial ( serial, pin ) VALUES ( '$f_serial', '$pin' )";
mysqli_query( $connection, $pin_serial_query );
}
While this will solve your immediate issue, as the number of rows grows you'll end up sending more and more SQL requests until you find an unused PIN. You will likely be happier with the result if you allow mySQL to generate a unique PIN for each new row.
if you want to write the serial into the row where the pin generated pin already sits (effectively overwriting the old serial that is already there, you would use an UPDATE statement:
... "UPDATE pin_serial SET serial='$serial'";
If you just want to skip this pin/serial combo I think yo already got the answer. Your code should work
Related
Currently working on a login script that would allow for multiple users with the same username to exist. The current plan is to generate a random "secret" user id that will take the place of the actual username. So how would I go about generating a random integer and checking to see if has been added?
This is my attempt at the code; however it does not seem to work as it does not seem to do anything.
$looptime = 100;
while ($looptime > 0) {
$userid = rand(0, 999999999);
$SQL = "SELECT * FROM Accounts WHERE username = '" . $userid . "'";
$result_id = #mysql_query($SQL) or die("DATABASE ERROR!");
$total = mysql_num_rows($result_id);
if (!$total) {
$looping = 0;
//CREATE THE ACCOUNT
mysql_query("INSERT INTO Accounts (id,username,password, email, money, activated) VALUES ('', '$username','$password', '$email', '0', '1')") or die("REGISTER ERROR!"); //1=account activated
//CONNECTED
echo "IMCONNECTED";
}
$looptime--;
}
EDIT: The code/number should be fairly easy to remember/jot down somewhere as the user will be able to view it and/or jot it down for account recovery purposes.
I would suggest either using a UUID/GUID (not an integer) to minimize the possibility of clashes, or using an identity column (not random) to guarantee uniqueness. Does it have to be an integer and does it have to be random?
Are you using an integer for the ID in the table? You could append this ID to the username. For example: MyUsername1234, MyUsername1245.
Here is a way you could do it. Create a scalar-variable function in your database (similar to below):
CREATE FUNCTION [dbo].[fn_randomNumber] (#guid nvarchar(128))
RETURNS int AS
BEGIN
SET #guid = REPLACE(#guid, '-', '');
DECLARE #idInt varchar(Max) = '';
DECLARE #i INT = 0;
DECLARE #char VARCHAR;
WHILE(#i < LEN(#guid))
BEGIN
SET #char = (SUBSTRING(#guid, #i, 1));
IF(ISNUMERIC(#char) = 1)
BEGIN
SET #idInt = #idInt + #char;
IF(LEN(#idInt) = 9)
BEGIN
BREAK;
END
END
SET #i = #i + 1;
END
RETURN CAST(#idInt as INT);
END
GO
Then execute this script:
SELECT [dbo].[fn_randomNumber] (
newid())
Of course you will want to evaluate the result to make sure it doesn't already exist.
I'm having problem with inserting in purchase table and updating facility table. Let's say, user made a purchase with product_id and product_quantity.
The query is running. But it inserts twice with the same data and not updating facility table.
When user hit submit, I want to insert product_id and product_quantity into purchase table. And updating facility table with product_id and product_quantity that associated with it.
Here is my code
<?php
include 'dbconn.inc.php';
include 'functions.inc.php';
$sql1 = "SELECT * FROM facilities";
$res = $mysqli->query($sql1);
$facilities = array();
while( $row = $res->fetch_array(MYSQLI_ASSOC) ){
$facilities[]['id'] = $facilities_id;
$facilities[]['product_id'] = $facilities_product_id;
$facilities[]['product_current_quantity'] = $product_current_quantity;
}
$id = $mysqli->real_escape_string ($_POST['id']);
$purchase_id = $mysqli->real_escape_string( $_POST['purchase_id'] );
$facility_id = $mysqli->real_escape_string( $_POST['facility_id'] );
$product_quantity = $mysqli->real_escape_string( $_POST['product_quantity'] );
$sql1 = "UPDATE facilities
SET
`product_current_quantity` = '$product_quantity + $product_current_quantity'
WHERE $facility_id = $facilities_id AND $id = $facilities_product_id ";
$sql = "INSERT INTO purchases
(
`purchase_id`,
`facility_id`,
`product_quantity`,,
`product_id`
)
VALUES
(
'$purchase_id',
'$facility_id',
'$product_quantity',
'$id'
)";
I did some research and I think I need to use triggers. But I never work with triggers before. Any helps would be great. Thank you!
Please execute your query and better use echo statement if you have doubt in query.
use "php.net"
used this code to your updates
product_current_quantity = product_current_quantity + $product_current_quantity
how many number they can add to your product Quantity and they sum the current number.
You have used insert query and update query for the same variable $sql without any condition. If so always your following query only executes.
Then anymore no update only insertion will reflect in your table.
$sql = "INSERT INTO purchases
(
`purchase_id`,
`facility_id`,
`product_quantity`,,
`product_id`
)
VALUES
(
'$purchase_id',
'$facility_id',
'$product_quantity',
'$id'
)";
Hey guys I am creating a table in mysql named result which will have 4 fields i.e.
table result
name ,
subject1_score ,
sub2_score ,
sub3_score
Now what I am doing is giving seperate forms to 3 teachers for entering their respective subject scores. For example, *teacher_1* will see all roll numbers and will be required to put subject1_score and then submit. Similarly for other two teachers. So what code I have to use in php and mysql in order to put values in a row for particular student.
i'm not sure what name stand for (student or teacher) and i'm assuming that there are 3 subjects and each teacher has to submit the respective score and you want all data to be set in one row like (roll_num, name, subject 1 score, subject 2 score, subject 3 score).
if that's ture then this should work for you:
if (isset("name") && isset("roll_number)){
$name = $_GET["name"];
$roll_no = $_GET["roll_number"];
if (isset("subject1_score")){
$subject = "subject1_score";
$score = $_GET['subject1_score'];
}elseif(isset("subject2_score")){
$subject = "subject2_score";
$score = $_GET['subject2_score'];
}elseif(isset("subject3_score")){
$subject = "subject3_score";
$score = $_GET['subject3_score'];
}else{
$subject = "";
$score = "";
}
$con = mysql_connect("host","username","password");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db($con, dbname);
$query1 = "SELECT * FROM result WHERE roll_number='$roll_no'";
$result1 = mysql_query($query1) or die(mysql_error());
$num = mysql_num_rows($result);
if($num == 0 && $subject != ""){
$query2 = "INSERT INTO result(roll_number, name, $subject) VALUES('$roll_no', '$name', '$score')";
mysql_query($query2) or die(mysql_error());
}elseif($num > 0 && $subject != ""){
$query2 = "UPDATE result SET $subject='$score' WHERE roll_number='$roll_no'"
}else{
echo "subject score is empty";
}
mysql_close($con);
There are two approaches, first you either fill the table with student names/roll_nos or second, you keep it blank. But please keep a field for roll numbers as they are unique and can serve you as primary keys.
In the first approach, you just have to edit the particular row for the particular roll no for whom the marks have been entered. For this you just need to run mysql's update query, like,
mysql_query("UPDATE table_name SET subject1_score='$subject!_score' WHERE roll_no='$roll_no'");
and so on. In here you have to fetch the roll no and marks from the form through PHP.
In the second approach, you have to first check if the roll no is present in the database table by running a SELECT query and counting the no of rows by `mysql_num_rows'. If the no of rows is more than 0, then you have to update the roll_no by running the update query. If the no of rows returned are 0, you need to insert the date by running the insert query.
Hope this helps!
At the moment im sending scores and data to my database from my flash game, though every level completed is a new record.
feilds are set out like l1Score,l2Score,l3Score
im trying to figure out how to update records if the field ipAddress and playerName match the current $varibles.
UPDATE highscores SET l2Score = '$l2Score' WHERE ipAddress = "$ipAddress" && playerName = '$playerName'
I was thinking somthing along these lines, but could someone point me in the right direction please!
First you want to perform a query to check if there is already a score in place for that user & IP.
$sql = "SELECT * FROM highscores WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
$result = mysql_query($sql, $con);
$row = mysql_fetch_assoc($result);
Now, if $row is empty then you want to insert a new record, else you want to update a previous record.
if($row == "")
{
$query = "INSERT INTO highscores (l2score, ipAdress, playerName) VALUES ('$l2score', '$ipAdress', '$playerName'";
} else {
$query = "UPDATE highscores SET l2Score = '$l2Score' WHERE ipAdress = '$ipAdress' AND playerName = '$playerName'";
You may need to edit this to fit with the specific query that you need.
say I have a variable
$id = mt_rand();
how can I query the mysql database to see if the variable exists in the row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?
Thanks you guys.
$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
mysql_select_db('<schemata>', $con);
$found = false;
while (!$found) {
$idIamSearching = mt_rand();
$query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
$result = mysql_fetch_row($query);
if ($result[0] > 0) {
mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
$found = true;
}
}
mysql_close($con);
}
Your description is hard to understand, so, this is something that could give you pointers...
'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'
make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters
then fetch the row and check if count is 1 or greater than 0
if one, then it exists and try again (in a loop)
although, auto increment on the id field would allow you to avoid this step
$bExists = 0;
while(!$bExists){
// Randomly generate id variable
$result = mysql_query("SELECT * FROM table WHERE id=$id");
if($result){
if(mysql_num_rows($result) > 0){
$bExists = 1;
} else {
// Insert into database
$bExists = 1;
}
}
1 Randomly generate id variable
2 Query database for it
2.1 Result? exit
2.2 No result? Insert