Can any one tell whats wrong with this query? - php

$sql = "select * from instalmentsdetails_ where studentFeeId='$savestudentfees' AND instalmentName='$instlnamefdtls'";
$query = $this->db->query($sql);
if($query->num_rows() > 0){
echo($id);
$this->db->where('instalmentsDetailsId',$id);
$this->db->update('instalmentsdetails_',$instldata);
}else{
echo($id);
$id='';
echo($id);
$sql= "INSERT INTO instalmentsdetails_` (`instalmentsDetailsId`, `studentFeeId`, `instalmentName`, `amount`, `dueDate`, `status`) VALUES ('$id', '$savestudentfees', '$instlnamefdtls', '$amtfdtls', '2011-10-06', '1')";
$id=$this->db->insert_id();
$query = $this->db->query($sql);
return $query;
}
return $id;
This query first checks if there are any rows present, if there is, it is going to update the old record, otherwise it is going to create a new record, but for some reason it does not work as expected even when the query returns num_row() > 0.It's a model in codeigniter

Have you checked the output of $query->num_rows()?, eg echo $query->num_rows()
You could do this instead and save the bother in PHP
ALTER TABLE teami_db ADD UNIQUE INDEX(studentFeeId, instalmentName);
Then you can perform an ON DUPLICATE KEY UPDATE query like so.
INSERT INTO `instalmentsdetails_teami` (
`instalmentsDetailsId`,
`studentFeeId`,
`instalmentName`,
`amount`,
`dueDate`,
`status`
) VALUES (
'$id',
'$savestudentfees',
'$instlnamefdtls',
'$amtfdtls',
'2011-10-06',
'1'
) ON DUPLICATE KEY UPDATE
`instalmentsDetailsId` = VALUES(`instalmentsDetailsId`),
`studentFeeId` = VALUES(`studentFeeId`),
`instalmentName` = VALUES(`instalmentName`),
`amount` = VALUES(`amount`),
`dueDate` = VALUES(`dueDate`),
`status` = VALUES(`status`)
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Related

MS SQL 2005 Auto Increment Error

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";
}}

MySQL "UPDATE" syntax is entering 0 in column

I am trying to enter into a table in with PDO if using an if condition. My code for the function is below:
function add_user_info($conn, $user, $info, $fName, $sName, $past, $pos){
// Prepare and execute statements
$info1 = addslashes($info);
$sql = $conn->prepare("SELECT * FROM `User_Info` WHERE `User` = '$user'");
$sql->execute();
if ($sql->fetch()){
// Update current entry
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info` = '$info1' AND `Past` = '$past' AND `Position` = '$pos' WHERE `User` = '$user'");
} else {
// Create new entry
$sql1 = $conn->prepare("INSERT INTO `User_Info` (`User`, `Info`, `FName`, `SName`, `Past`, `Position`) VALUES ('$user', '$info1', '$fName', '$sName', '$past', '$pos')");
}
$sql1->execute();
}
The ONLY (I repeat, ONLY) part that is not working for me is on line 9 with the update query. I have narrowed the problem down to it being related with the update of the Info column, and not only that but it is a problem with the string so the variable $info1.
I am trying to pass in a string of text from CKEditor. It is a rich text string and so has HTML tags, quotations, etc in it when passed to the SQL.
The initial creation of the row in the table (line 12 of the function) works PERFECTLY so it is only on the update that the string is seen as funny. When I update with a word in place of $info1 it still does not work.
As shown in phpmyadmin, my table schema is as follows:
Update command multiple set is separated by , not and
UPDATE `User_Info`
SET
`Info` = '$info1' ,
`Past` = '$past' ,
`Position` = '$pos'
WHERE `User` = '$user'"
Change AND to ,
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info`='$info1', `Past`='$past', `Position`='$pos' WHERE `User`='$user'");

SQL insert and update in the same time

Hey I have a query that will insert into the table a new data and I want that in the same time update an outher table with the id of the new data that I have entered. ex:
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$query = mysql_query("SELECT `id` FROM `test` WHERE `name` = 'Mark'");
$id = mysql_result($query,0);
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
How do I do it at same time? because doing it this way I only insert the new data and I dont update the other.
Cumps.
Try this :
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
I've changed the backticks to single quotes in your first insert for the values, backticks should never be used for field values.
Also I've changed it to use only two queries, the mysql_insert_id() will get the last inserted id without you needing to query it.
Ref : http://www.php.net/manual/en/function.mysql-insert-id.php
First of all, you do not need the select to get the id, there is mysql_insert_id() for that.
Then you have to use a transaction to make both queries feel like executed at the same time:
mysql_query('BEGIN');
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_query("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
mysql_query('COMMIT');
A transaction makes sure both statements are executed, and no other script can come between them in any way.

mysqli returns true for INSERT query, row not inserted

if ($word != '' && $text != '') {
$result = $conn->query("SELECT * FROM variables WHERE `word` = '$word'");
if ($source = $result->fetch_assoc()) {
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
if ($result = $conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')"))
echo 1;
}
}
The above is the INSERT code (and update) the UPDATE code works fine, however when the INSERT query is called the query returns true but when i check the data, it hasn't been inserted.
Any help is appreciated, thanks in advance.
EDIT:
variables table structure:
`word` varchar(100) NOT NULL, //also PRIMARY KEY
`text` text NOT NULL
You have a single = in an if condition.
maybe you wanted:
if ($result->num_rows){ // see if there are any rows
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
$conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')");
echo 1;
}
tested:
$conn = new mysqli('localhost', 'root', '', 'test');
$word = 'word1';
$text = 'text1';
$result = $conn->query("SELECT * FROM variables WHERE `word` = '$word'");
if ($result->num_rows){
$conn->query("UPDATE variables SET `text` = '$text' WHERE `word` = '$word'");
echo 0;
} else {
$conn->query("INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')");
echo 1;
}
I've been struggling with the same problem but solved it in a different way.
Check how many rows are affected, like this (this example uses mysqli but I hope you'll get the point):
$number_of_rows_affected = mysqli_affected_rows($conn);
If $number_of_rows_affected = 0 then INSERT wasn't working. A number larger than 0 means a successful INSERT.
Not sure why you use backticks around 'word' and 'text' in your query.
For debugging this, I write the query to a string and print it before executing it, to make sure the query is what I wanted, so use:
$query = "INSERT INTO variables (`word`, `text`) VALUES ('$word', '$text')"
print("$query")
if ($result = $conn->query($query))
echo 1;
Are you sure the insert does not work? Do you close your database connection before you check, maybe the results have just not been committed to your database when you check?

Adding rows to mysql - get sorted randomly - want them on top

I have kind of a "problem" that I do not know how it happened. If I add rows to my table via php it just adds them randomly somewhere. But I want them to be added on top. Instead it justs add them all over the table.
$name = ($_GET["name"]);
$sql = "INSERT INTO $DB_Table VALUES('$name')";
$number = ($_GET["number"]);
$sql = "INSERT INTO $DB_Table VALUES('$number')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_query("INSERT INTO $DB_Table (Name,number)
VALUES ('$name','$m_yolo')");
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
There is no such thing as row ordering in a relational table. If you want them ordered, you need to use an ORDER BY clause. You can add a TIMESTAMP column, which you can sort on when you select your data: 11.3.1. The DATE, DATETIME, and TIMESTAMP Types
Create another table but add an ID auto-increment column in it:
CREATE TABLE IF NOT EXISTS `table` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`number` int(10) NOT NULL,
PRIMARY KEY (`id`)
);
Then you can insert new rows like this:
$sql = "INSERT INTO $DB_Table (id, name,number) VALUES ('', '$name', '$number')";
Your new entries will be sorted by id then. You can order them in you select query with:
$sql = "SELECT 'name', 'number' FROM `table` ORDER BY 'id' DESC";
One remark about your code though: it is not safe to directly use the values from $_GET as you do at the beginning of your code. Try using mysql_real_escape_string() for example.

Categories