If i'm doing multiple mysql queries on the same table, occasionally some get skipped.
Why is that?
For example:
<?php
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
?>
Sometimes one of the queries will not be executed?
Why is that?
-Or is it something wrong with my server not general mysql?
(Obviously I know now to update the same table in the same query, but before that I was very confused as to why it happens, can anyone please explain?)
Thanks!
You do not need to make 3 queries, if you are updating the same rows:
$q = "
UPDATE table
SET field = '',
field2 = '',
field3 = 0
WHERE Id = :id
";
$statement = $pdo->prepare( $q );
$statement->bindParam(':id', $something, PDO::PARAM_INT);
$statement->execute();
Also, you should stop using the ancient mysql_* functions. They are not maintained anymore and process for deprecation has already begun.
Maybe you should avoid the 10+ year old API and learn something for this decade: PDO Tutorial for MySQL Developers.
debug your code to see if a query fails:
$result = mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Use the following to debug the code:
mysql_query("UPDATE `tb` SET `field` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field2` = '' WHERE `Id` = '$something'") or die(mysql_error());
mysql_query("UPDATE `tb` SET `field3` = '0' WHERE `Id` = '$something'") or die(mysql_error());
UPDATE
Make sure you are escaping $something using:
$something = mysql_real_escape_string($something);
Related
Here is what I am trying to do (in pseudo code)
if (dB entry exists) {
UPDATE the dB entry
}else{
UPDATE a default dB entry
}
This is not a "INSERT INTO ... ON DUPLICATE" question.
I'm hoping there is some kind of UPDATE ... ON DUPLICATE type of slick code to do this in one line.
My code creates $userName from the $_GET['U'] request. If $userName exists in the database (it's a unique key), then increment a counter in the database. Else, increment a counter for a default entry.
Here is my current code to update the counter:
$userName = $_GET['U'];
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = '" . $userName . "'";
mysqli_query($conn,$sql);
And if this particular username doesn't exist, I want this to happen:
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = 'default'";
mysqli_query($conn,$sql);
Are you looking for this,
$userName = $_GET['U'];
$query_uname_exists = "SELECT count(*) FROM stats WHERE `userName` = '" . $userName . "'";
$uname_count = mysqli_query($conn,$query_uname_exists);
if($uname_count > 0){
#update
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = '" . $userName . "'";
mysqli_query($conn,$sql);
}
else{
#update default
$sql = "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = 'default'";
mysqli_query($conn,$sql);
}
Use the following query
$sql = "Update stats SET count = count + 1 where username = (case when username= ". $userName ". then username else 'default' end)";
This is the most I can shrink it for you:
$userName = mysqli_query($conn, "SELECT count(*) FROM stats WHERE `userName` = '".$_GET['U']."' LIMIT 1") == 0 ? 'default' : $_GET['U'];
mysqli_query($conn, "UPDATE `stats` SET `count`= `count` + 1 WHERE `userName` = '".$userName."' LIMIT 1");
I have an UPDATE query and using Ajax, I wanted to know if any value is empty can I only update the values that not empty in the database. I don't know if this is possible to have a if statement or something to check to skip the empty values. I know I can just add another form element but just wanted to know if there was another solution.
Only if the data is POST from front end form. If data not POST don't update this Title = '.$title .',
$id = $_POST['id'];
$title = "";
$description = $_POST['Description'];
$date = $_POST['Date'];
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = '.$title .',
`Description` = '.$description.',
`Date` = '.$date =.'
WHERE `id` = '.$id;
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
Update: This is what worked for me. Thanks Karim Daraf
$query = " UPDATE user SET
Title = Coalesce($title,Title ) etc...
Try it with Coalesce .
$query = " UPDATE user
SET
`Title` = CASE WHEN `Title`='' or `Title` IS NULL THEN '$title' END,
`Description` = CASE WHEN `Description`='' Or `Description` IS NULL THEN '$description' END,
`Date` = CASE WHEN `Date`='' Or Date` IS NULL THEN '$date' END
WHERE `id` = '".$id."' ";
or :
$query = " UPDATE user
SET
`id` = Coalesce('$id''".$id."' , NULLIF(`id`,'')),
`Title` = Coalesce('$title''".$title."',NULLIF(`Title`,'') ) ,
`Description` = Coalesce('$description''".$description."' , NULLIF(`Description`,'') ) ,
`Date` = Coalesce('$date''".$date."',NULLIF(`Date`,''))
WHERE `id` = '$id''".$id."' ";
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = COALESCE(NULLIF("'.$title.'", ""),`Title`),
`Description` = "'.$description.'",
`Date` = "'.$date.'"
WHERE `id` = "'.$id.'"';
Not sure to understand: you have data and want to update, but only if some fied in the DB are empty?
In the case perfom only a where:
$query = 'UPDATE user SET
`id` = '.$id.',
`Title` = '.$title .',
`Description` = '.$description.',
`Date` = '.$date =.'
WHERE `id` = '.$id.' AND Title = '';
for example
$sql = "UPDATE `shows` SET `title` = '$title', `tagline` = '$tagline', `desc` = '$desc' , `img_src = '$imgsrc' WHERE id = $showid";
The query above does not want to work, I simply get a mysql_error saying error at '' on line 1;
Any idea where I am going wrong?
You're missing a tick:
`img_src = '$imgsrc' WHERE id = $showid";
should be:
`img_src` = '$imgsrc' WHERE id = $showid";
MySQL/PHP:
For a query with multiple statements, which deletes rows in four different tables, I want to know the combined number of affected rows. The PHP manual says I'll only get the result from the last 'operation', which suggests it will only tell me how many rows were affected by the last of the DELETE statements.
How to get around this?
$deleteContactSQL = "DELETE FROM `persons` WHERE `persons`.`id` = '$person' AND `owner = '$user' AND `userOrContact` = 'contact';
DELETE FROM `tabs` WHERE `person` = '$person' AND `ownerIdentity` = '$user' AND `selfOrOther` = 'other';
DELETE FROM `tabAccess` WHERE `person`= '$person' AND `givenToIdentity` = '$user';
DELETE FROM `personAccess` WHERE `viewedPerson` = '$person' AND `viewerIdentity` = '$user';
;";
include $_SERVER['DOCUMENT_ROOT'].'/goalview/includes/db.inc.php';
$deleteContacts = mysqli_query($link, $deleteContactSQL);
$success = mysqli_affected_rows($link);
Something like this maybe?
include $_SERVER['DOCUMENT_ROOT'] . '/goalview/includes/db.inc.php';
$sql = array();
$sql[] = "DELETE FROM `persons` WHERE `persons`.`id` = '$person' AND `owner = '$user' AND `userOrContact` = 'contact';"
$sql[] = "DELETE FROM `tabs` WHERE `person` = '$person' AND `ownerIdentity` = '$user' AND `selfOrOther` = 'other';"
$sql[] = "DELETE FROM `tabAccess` WHERE `person`= '$person' AND `givenToIdentity` = '$user';"
$sql[] = "DELETE FROM `personAccess` WHERE `viewedPerson` = '$person' AND `viewerIdentity` = '$user';"
$aff_rows = 0;
foreach($sql as $current_sql)
{
$deleteContacts = mysqli_query($link, $current_sql);
$aff_rows = $aff_rows + mysqli_affected_rows($link);
}
Here is a compact, procedural-style mysqli_multi_query() solution for counting combined affected rows:
$deleteContactSQL="DELETE FROM `persons` WHERE `id`='$person' AND `owner='$user' AND `userOrContact`='contact';
DELETE FROM `tabs` WHERE `person`='$person' AND `ownerIdentity`='$user' AND `selfOrOther`='other';
DELETE FROM `tabAccess` WHERE `person`='$person' AND `givenToIdentity`='$user';
DELETE FROM `personAccess` WHERE `viewedPerson`='$person' AND `viewerIdentity`='$user';";
include $_SERVER['DOCUMENT_ROOT'].'/goalview/includes/db.inc.php';
if(mysqli_multi_query($link,$deleteContactSQL)){
do{
$success+=mysqli_affected_rows($link);
}while(mysqli_more_results($link) && mysqli_next_result($link));
}
Alternatively, this group of queries may be a good candidate for some TRIGGERs in the persons table.
I'd be doing it like this, but, I do like to keep things simple which not everyone can appreciate ;)
$deleteContactSQL = sprintf("call cascade_delete_persons(%d,%d)", $person, $user);
$deleteContacts = mysqli_query($link, $deleteContactSQL);
drop procedure if exists cascade_delete_persons;
delimiter #
create procedure cascade_delete_persons
(
in p_pid int unsigned,
in p_oid int unsigned
)
begin
declare v_persons_count int unsigned default 0;
declare v_tabs_count int unsigned default 0;
delete from persons where id = p_pid and owner = p_oid and userOrContact = 'contact';
set v_persons_count = row_count();
delete from tabs where person = p_pid and ownerIdentity = p_oid and selfOrOther = 'other';
set v_tabs_count = row_count();
-- etc...
select v_persons_count as person_count, v_tabs_count as tabs_count;
end #
delimiter ;
You can use this method too if you must : http://php.net/manual/en/mysqli.multi-query.php
My question is how can I be sure of a row that I'd like to return is exists? I don't want to suppress it with PHP's # option or count rows before every query to find out the row is exists or not.
So there's a simple query like this:
"SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
and the table cannot contain the row with id 234.
You don't have to count rows before every query - generally you do it after.
What about something like this
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$results = mysql_query($query);
if (mysql_num_rows($results)) {
// do something because it was found
}
You're probably using mysql_result() to fetch the fields. Consider mysql_fetch_array instead. It returns FALSE if there are no more rows to fetch.
<?php
$mysql = mysql_connect('..', '..', '..') or die(mysql_error());
mysql_select_db('..', $mysql) or die(mysql_error());
$query = "SELECT `title`, `id` FROM `event` WHERE `id` = '234'";
$result = mysql_query($query, $mysql) or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo 'no such record';
}
else {
echo $row['title'], ' ', $row['id'];
}