MS SQL 2005 Auto Increment Error - php

So, I have tried to create a table inside my database 'Test',
CREATE TABLE TestTbl(
id INT IDENTITY(1,1),
Agent_id VARCHAR(255) NOT NULL
)
After it was created, I tried to add 2 values for the agent via php, but the result is this:
id | Agent_id
0 8080
0 8081
It does not auto increment, even if I set 'id' as a Primary key, still the problem occurs, anyone knows how to solve this problem?
Here is my insert statement in php, nevermind the $conn, because it works, it is for my sql connection
if(isset($_POST['agentid'])){
$agent = $_POST['agentid'];
$query = "SELECT * FROM [Test].[dbo].[TestTbl] WHERE [Agent_id] = '$agent'";
$result = sqlsrv_query($conn,$query);
if(sqlsrv_has_rows($result) !=0){
echo "ID EXISTS";
}else{
$sql = "SET INDENTITY_INSERT TestTbl ON
INSERT INTO [Test].[dbo].[TestTbl]
([id],[Agent_id]) VALUES ('','$agent')
SET IDENTITY_INSERT TestTbl OFF";
echo "Added";
}}

Change this part
From
INSERT INTO [Test].[dbo].[TestTbl]
([id],[Agent_id]) VALUES ('','$agent')
To
INSERT INTO [Test].[dbo].[TestTbl]
([Agent_id]) VALUES ('$agent')
When it's auto increment, you don't' need to specify that in your INSERT statement.
Also do not SET IDENTITY_INSERT to OFF when you want to use auto increment feature of your table
SET IDENTITY_INSERT allows explicit values to be inserted into the identity column of a table.
Your complete query
if(isset($_POST['agentid'])){
$agent = $_POST['agentid'];
$query = "SELECT * FROM [Test].[dbo].[TestTbl] WHERE [Agent_id] = '$agent'";
$result = sqlsrv_query($conn,$query);
if(sqlsrv_has_rows($result) !=0){
echo "ID EXISTS";
}else{
$sql = "INSERT INTO [Test].[dbo].[TestTbl]
([Agent_id]) VALUES ('$agent')";
echo "Added";
}}

Related

Create Table In PDO Transaction

How can I fix this transaction so that the pdo query makes a new table in step #4?
The first three steps work, but I can't seem to get #4 to work.
STEPS
Finds a user with a chattingstatus of 0 in the database
Add a user into the database (with predetermined variables)
change the chattingstatus from 0 to 1 for both the user with a 0 status and the inserted user
4. Create a table with the id of both users as the title like this 2+13 (2 being the id and 13 being the id)
$userid = "123456";
$firstname = "Dae";
$oglang = "engs";
$status = 0;
$pdo->beginTransaction();
try{
// Find a user with a status of 0
$sql = "SELECT id FROM users WHERE chattingstatus = :status";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':status' => $status)
);
$freeuser = $stmt->fetchColumn();
//put the original user into the database with userid firstname and language
$sql = "INSERT INTO users (userid, firstname, oglang, chattingstatus) VALUES (:userid, :firstname, :oglang, :chattingstatus)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':userid' => $userid, ':firstname' => $firstname, ':oglang' => $oglang, ':chattingstatus' => 0)
);
$ogID = $pdo->lastInsertId();
// change the chattingstatus of 0 of the free user to 1
$sql = "UPDATE users SET chattingstatus = 1 WHERE id = :freeuser";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':freeuser' => $freeuser)
);
//query 3 CHANGE STATUS OF ORIGINAL USER from 0 to 1
$sql = "UPDATE users SET chattingstatus = 1 WHERE userid = :oguser";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':oguser' => $userid)
);
//query 4: Make a table between the 2 users with their IDs
$table = $freeuser."+".$ogID;
$sql ="CREATE table $table(
ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
Messages VARCHAR( 50 ) NOT NULL);";
$stmt = $pdo->exec($sql);
print("Created $table Table.\n");
$pdo->commit();
}
//Our catch block
catch(Exception $e){
//Print out the error message.
echo $e->getMessage();
//Rollback the transaction.
$pdo->rollBack();
}
Thanks in advance.
Since your table name includes the special character +, you need to put it in backticks to quote it.
$sql ="CREATE table `$table` (
ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
Messages VARCHAR( 50 ) NOT NULL);";
You'll need to remember to put backticks around the table name whenever you use it in other queries. If you insist on having per-user tables like this, you might want to use a different character to connect them, like underscore.
Creating table in transation doesn't work in MySQL:
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Source: https://www.php.net/manual/en/pdo.begintransaction.php

SQL Select/ Insert / Update query PHP MySQL

I have a table with columns userID(int),timeIN(date),timeOUT(date)
I am inserting a record in mysql database. First I check if the userID is correct from the other table and if its correct it will add a new record of the userID and timeIN(date) whereas the timeOUT will be NULL, else it will display error if the userID is not correct. I want my code to be able to check if the user is currently timeIN so it will prevent a double entry. I would also like to insert or update timeOUT(date) if the values of userID is equals to the user input and timeIN is not null and timeOUT is null.
Please kindly help...thanks.
Here is my code for inserting userID and timeIN: IT WORKS when inserting into mysql database.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('dbConnect.php');
$userID = $_POST['userID'];
$sql = "SELECT * FROM employee WHERE userID='$userID'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check)){
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
echo 'Time IN Successful!';
}else{
echo 'Invalid USER ID. Please try again!';
}
mysqli_close($con);
}
?>
You should handle these checks inside the database. The current check you are doing in the database can be handled by a foreign key constraint:
alter table dtr add constraint fk_dtr_userId
foreign key (userId) references employee(userId);
The second means that you want only one row with a NULl value. Ideally, this could be handled with a unique constraint:
alter table dtr add constraint unq_dtr_userId_timeOut
unique (userId, timeOut);
Unfortunately (for this case), MySQL allows duplicate NULL values for unique constraints. So, you can do one of two things:
Use a default value, such as '2099-12-31' for time out.
Use a trigger to enforce uniqueness
In either case, the database itself will be validating the data, so you can be confident of data integrity regardless of how the data is inserted or updated.
I did it from my mobile not tested but you will get the idea of what is going on
if(isset($check))
{
$sql="SELECT * FROM dtr WHERE userID = $userID";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo "Already in";
if(isset($check['timeIN']) && !isset($check['timeOUT']))
{
$sql = "UPDATE dtr SET timeOUT= now() WHERE userID=$userID";
mysqli_query($con, $sql);
mysqli_close($con);
}
}
else
{
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
mysqli_close($con);
echo 'Time IN Successful!';
}
}
else
{
echo 'Invalid USER ID. Please try again!';
mysqli_close($con);
}

Adding constant to values in Mysql and updating the values to the result

I have got MySQL table with three columns 'primary Key','debit_cash','user_id' So now i want to update the debit_cash values to the corresponding user_id by adding "15" to the value already present. The debit_cash is in VARCHAR so i tried converting to int and sum it , but still the values in MySQL is not changing .
Here is my code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$user_id = $_POST['user_id'];
//importing database connection script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT cos_details.debit_cash AS debitCash,
(convert(int, debit_cash)+15) AS updatedDebitCash
FROM cos_details
UPDATE cos_details SET debit_cash = '$updatedDebitCash'
WHERE user_id = $user_id";
//Updating database table
if(mysqli_query($con,$sql)){
echo 'Updated Successfully';
}else{
echo 'Could Not Update Try Again';
}
//closing connection
mysqli_close($con);
}
Any one please help me.
Seems that you don't need the select but the update only
UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
WHERE user_id = $user_id
could be that your user_id is a string too so you should surround the value with quote
UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
WHERE user_id = '$user_id'

Why wont this MySQL Query save

So I have this short script. Its not giving out any error but it will not save into the DB. After I run the script I check the DB and nothing is there.
The db only has two items. (id and fid) ID is set at INT 11 auto and fid is set at VARCHAR 64. Also, I am connecting to my DB just fine.
<?php
$con = mysqli_connect('####', '####', '####', '#####');
if (mysqli_connect_errno()) {
echo 'Failed to Connect to MySQL' . mysqli_connect_errno();
}
if (isset($_POST['submit'])) {
$fid = $_POST['fid'];
$query = mysqli_query($con, "SELECT * FROM fid where fid = '$fid'");
$row = mysqli_num_rows($query);
if ($row == 1) {
echo 'This Federal Tax ID is already in use.';
} else {
mysqli_query($con, "INSERT INTO `fid` (id, fid) VALUES ('', '$fid')");
}
}
?>
Based on your comment:
It's supposed to be an empty value so the ID auto increments everytime.
That's not how auto-increment works. Your code is explicitly telling the record to not have a value:
"INSERT INTO `fid` (id, fid) VALUES ('', '$fid')"
If the id column is required, this will expectedly fail. (It may also be failing based on the type. You're trying to insert a string, but an auto-increment column would be numeric...)
An auto-increment column doesn't need to be supplied an empty value. Just omit it entirely:
"INSERT INTO `fid` (fid) VALUES ('$fid')"
Additionally, this code is wide open to SQL injection. You're going to want to read up on that. In short, you should use prepared statements which bind to user-input values. Don't concatenate those user-input values directly into your code, that allows the user to inject their own code.
If you want to use AUTO you need to either NOT specify the value at all or else specify a 0 (or NULL if defined as NOT NULL):
Either
INSERT INTO fid (fid) VALUES ('$fid')
or
INSERT INTO fid (id, fid) VALUES (0, '$fid')
or (if id is defined as NOT NULL)
INSERT INTO fid (id, fid) VALUES (NULL, '$fid')
SOURCE: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Update/Insert into mysql query

I am trying to perform a update/insert into query for MySQL. Should insert, if not already in database.
However, it will not update. My db connection is good. I cannot figure it out.
$sql = "UPDATE jos_bl_paid SET u_id='$uid', m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND '$mid' = m_id ";
$test45 = mysql_affected_rows();
if ($test45 == 0) {
$sql = "INSERT INTO jos_bl_paid(paypal_payment,u_id,m_id,pd,t_id,p_date)VALUES('$txn','$uid','$mid','1','$cus',NOW())";
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
echo 'Yes';
}else{
echo 'No';
}
From the code you are showing you aren't even running the update query. You need to put
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
before the line
$test45 = mysql_affected_rows();
for that to even return what you want
I would make these into one statement using the ON DUPLICATE KEY UPDATE mysql command. I would guess that your problem is that the insert may be failing because of some unique key set in you schema even though the actual uid doesn't yet exist so the update also fails. Can you post exactly what error message you get?
check your last value in update query i found an error there and have fixed it from my side
try this
$sql = mysql_query("UPDATE jos_bl_paid SET u_id='$uid',m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND m_id = '$mid'") or die(mysql_error());
Answer is updated try the updated one
From the code you posted, it appears that you're setting the $sql string to an update statement, but not executing it before checking for the number of affected rows.
You'll probably need to call mysql_query($sql) before checking mysql_affected_rows();
Otherwise you're not telling the database to update anything.
If the new values in update are the same as old one mysql won't update the row and you will have mysql_affected_rows be 0. If you have primary key on fields u_id, m_id you can use INSERT ON DUPLICATE UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you don't have such you may use the count query:
SELECT count(*) FROM jos_bl_paid WHERE u_id = '$uid' AND '$mid' = m_id
To decide if you should update or insert new one.

Categories