Okay, I'm currently sick so maybe the answer is right in front of me but I've been sitting here for the past 4 hours trying to figure out why this is happening.
Basically I have a script that is supposed to update a row in the database.
The field I'm trying to update is 'name' and it looks like this:
// Updating the database with the new name
$name = $this->db->slashes( $this->friends[$row->key] );
$sql = "UPDATE `friends` SET `name` = '" . $name . "' AND `status` = 'updated' WHERE `key` = " . $row->key . " LIMIT 1";
echo '-- Query: ' . $sql . '<br />';
$result2 = $this->db->query( $sql );
if( !$result2 )
echo mysql_error();
Output becomes this(an example):
-- Query: UPDATE `friends` SET `name` = 'Andrew Johnsson' AND `status` = 'updated' WHERE `key` = 7823583 LIMIT 1
It did not generate any mysql_error so the query seem to have gone through properly and by the looks of the query, it should have just updated a row in the database where the key was a number and set the new name to Andrew Johnsson aswell as setting status to updated.
However! After looking in the database after this update, the name for this row is set to '0'. Why on earth did it do that?
Any ideas as to why this is happening?
Also, tell me if you need some more information to be able to help me and I'll kindly provide it!
Your UPDATE syntax is incorrect. It should be SET name = 'string', status = 'updated' WHERE key...
Currently you are literally asking it to evaluate the AND's in order to determine what the name column should be updated with, which is why you're getting the 0.
Well, this might be too silly, but name is a string field, right? If it's set to any kind of integer field, this is exactly what would happen: the string is parsed as 0.
I bet it's something a wee bit more complicated than that, though.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am checking the for the user_id (it is held in a session) - this is working. Then I am running a SELECT query for that user for the database table click_count. I am checking to see if that user has any records within it, ie: $page_count. If not, I want my INSERT statement to run to add that user to the database table along with other data.
The part I do not understand is it seems that my UPDATE query is always running. For example no matter which user I login with my query only updates the only user in the database table. IE: Bob is the only user in the click_count table, if I log in with Pete, Bob's record is being updated.
I have tested the value for $page_count and it equals 0, so my INSERT should be running. I have also tried if ($page_count === 0) {
Does anyone see anything I am missing?
$curPage = $_SERVER['PHP_SELF'];
$clicks = 0;
$setup = 0;
$page_total_count = 0;
var_dump($user_id);
$click_sql = "
SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$click_stmt = $con->prepare($click_sql);
$click_stmt->execute(array($user_id, $curPage));
$click_stmt_rows = $click_stmt->fetchAll(PDO::FETCH_ASSOC);
$page_count = $click_stmt->rowCount();
foreach ($click_stmt_rows as $click_stmt_row) {
$setup_status = $click_stmt_row['setup'];
$page_total_count = $click_stmt_row['page_count'];
}
if ($page_count == 0) {
$click_insert_sql = "
INSERT INTO click_count
(user_id, page_url, page_count, setup)
VALUES(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE page_count=page_count+1;
";
$click_insert_stmt = $con->prepare($click_insert_sql);
$click_insert_stmt->execute(array($user_id, $curPage, 1, $setup));
}
else {
$click_update_sql = "
UPDATE click_count
SET page_count=page_count+1
WHERE user_id = ?
AND page_url = ?
";
$click_update_stmt = $con->prepare($click_update_sql);
$click_update_stmt->execute(array($user_id, $curPage));
}
Table
click_count
CREATE TABLE `click_count` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`page_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`page_count` int(11) NOT NULL,
`setup` int(5) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
UNIQUE KEY `page_url` (`page_url`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Since there is only the one user in the table, there is no record "to insert/update", therefore
ON DUPLICATE KEY UPDATE failed you silently.
A regular UPDATE will suffice:
I.e. and as an example:
UPDATE table SET col_x = 0|1 WHERE col_y = ? // (boolean 0-1)
Note:
If ever you wish to increase a column by counting later on, the syntax would be:
UPDATE table SET col_x = col_x + 1 WHERE col_y = ?
In regards to your asking about how you could improve on your code:
#Fred-ii- Thanks. Yes, it is working now how I want, but if there are ways to improve the code I am always willing to try to learn it. I just remembered people in the past saying that I didn't need the update query at all with the duplicate key update. – Paul
You could use named placeholders :name rather than ? since they are easier to keep track of, but this is of course a matter of opinion that I feel is also shared by many and not just myself.
Footnotes/credits:
I would like to also give credit to the following comment:
"If you always fall into update indicates that $page_count is not zero.. Try to echo() it to see maybe.. I would probably first try to add another user into click_count table and then it may become easier to see where it goes wrong.. – johnyTee"
where the OP responded with:
"#Fred-ii- I figured it out. I used johnyTee's advise and tried adding another user to the database manually and it wouldn't let me because of the unique index for the page_url column. I then removed the unique index from it and now it works perfectly. Thanks for the help! – Paul"
from PHP PDO doc http://php.net/manual/en/pdostatement.rowcount.php
PDOStatement::rowCount() returns the number of rows affected by a
DELETE, INSERT, or UPDATE statement.
if you need th number of rows in select you should use somethings like
$sql = "SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
It may be '0' (a string). You can use intval to convert it to an integer.
$page_count = intval( $click_stmt->rowCount() );
http://php.net/manual/en/function.intval.php
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
try like this:
$sql = "SELECT count(*)
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
//insert
}else {
//update
}
}
I have a problem with an sql query i want to run. Basically I want to update a table only if it has no '.' in it (for example 1 row has value '2' and the other row will have value '2.1', in this case i would only want to update the value with a 2.) This is what I tried
UPDATE new__tags SET sort_order = 1 WHERE id = '.$id. ' AND sort_order NOT LIKE "%.%"';
Unfortunately this did not work and still updated everything.
Thanks for your time.
If your sort_order is an INT , use CAST
"UPDATE `new__tags` SET `sort_order` = 1 WHERE `id` = '.$id. ' AND CAST(`sort_order` as CHAR) NOT LIKE '%.%'";
Try this:
"UPDATE new__tags SET sort_order = 1 WHERE id = $id AND CAST(sort_order AS CHAR) NOT LIKE '%.%'";
try this i tested with phpmyadmin
"UPDATE new__tags SET sort_order = 1 WHERE id = $id AND sort_order NOT REGEXP '[.]'";
I am trying to update a field when particular function is called but its value is not getting updated in db . And also no errors showing up . Field type is text .
I tried by adding new field to table and then updated that field in my query and it worked fine, but after some time same issue with new field .
$con=mysqli_connect("localhost","username","password","dbname");
mysqli_query($con,"UPDATE sales_flat_quote SET extra_params = 'aaa',new_params = 'bbb' WHERE entity_id = 362214") or die(mysqli_error($con));
Above query was working earlier but later it doesn't update the value in database and if you run query directly on phpmyadmin it works fine .
Any Ideas ?
There's an error in your syntax, you forgot to close the double quote:
mysqli_query($con,"UPDATE sales_flat_quote SET extra_params = 'aaa',new_params = 'bbb' WHERE entity_id = 362214") or die(mysqli_error($con));
This should work. Syntax coloring is your friend ;)
Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks!
MySQL code.
SELECT *
FROM names
WHERE name = '" . $_POST['name'] . "'
AND userID = '$userID'
Here is the MySQL table.
CREATE TABLE names (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userID INT NOT NULL,
name VARCHAR(255) NOT NULL,
meaning VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
If $_POST['name'] is actually an array of strings, as you say, then try this PHP:
$namesString = '';
foreach ($i=0; $i < count($_POST['name']) $i++)
{
$namesString .= "'" . mysql_real_escape_string($_POST['name'][$i]) . "'";
if(isset($_POST['name'][$i + 1]) $nameString .= ', ';
}
With this query:
SELECT * FROM `names`
WHERE `name` IN ( $namesString )
AND `userID` = '$userID'
The query will return all the rows in which the name is the same as string in $_POST['name'].
First of all, if the userID field is unique, you should add a unique index on it in your table.
Also, watch out for SQL injection attacks!
Using something like this is much more secure:
$sqlQuery = sprintf('SELECT COUNT(id) AS "found" FROM names WHERE userID = "%s"', mysql_real_escape_string($_POST['name'], $conn));
This SQL query will return 1 row with 1 field (named found) which will return you the number of matched rows (0 if none). This is perfect if you only want to check if the userID exists (you don't need to fetch all data for this).
As for the dynamic array, you will have to post more information and I'll update my answer.
Meanwhile here are some usefull PHP functions that can help you do what you want:
For MySQL queries:
mysql_connect
mysql_real_escape_string
mysql_query
mysql_fetch_assoc
For your list of users:
explode
implode
Stated as you say, I'm quite sure the code does exactly what you are asking for. The SELECT should return the records that respond both to the name sent and the current user ID.
If you need some php code, here it is (should be refined):
$result = mysql_query('YOUR SELECT HERE');
if (!$result) {
die('ERROR MESSAGE');
} else {
$row = mysql_fetch_assoc($result));
// $row is an associative array whose keys are the columns of your select.
}
Remember to escape the $_POST.
I have a form which to insert data into a database. This form takes the content of the fields, and then displays the result page showing the entered information in context. There is a link on this page to edit the user info, which go back to the previous form. Obviously, I do not want duplicate records inserted. Is there an easy way to use an update statement if a record already exists? I am doing this with ajax and php.
Take a look at:
INSERT ... ON DUPLICATE: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
REPLACE INTO: http://dev.mysql.com/doc/refman/5.0/en/replace.html
INSERT ... ON DUPLICATE will allow you to issue an UPDATE query when a UNIQUE INDEX or PRIMARY KEY is matched.
REPLACE works exactly the same, but if the row is found, the old row is deleted prior to inserting a new one. When using cascading deletes, this is especially something to take into account!
MySQL supports the addition of ON DUPLICATE KEY UPDATE to an INSERT statement, which should do what you want.
Assuming you have a field like 'username' or 'email', you could make use of that field to check if a record already exists, if it does, update it.
$res = mysql_query("SELECT primary_key FROM my_table WHERE `email` = '" . mysql_real_escape_string($email) . "'");
if($row = mysql_fetch_array($res))
{
// Record exists, update it
$q = "UPDATE my_table SET `username` = '" . mysql_real_escap_string($username) . "' WHERE primary_key = " . (int) $row['primary_key'];
}
else
{
// Record doesn't exist, insert
$q = "INSERT INTO my_table(username, email) VALUES('" . mysql_real_escape_string($username) . "', '" . mysql_real_escape_string($email) . "');";
}
In the above example I assume you have a primary key field that's an integer (primary_key).
You should consider using an ORM like http://www.ezpdo.net/blog/?p=2
Plain SQL in web applications should only be used if absolutely neccessary, alone for security reason, but also to avoid problems like yours.