i have written few codes to show time spent by users at site but when a users click on submit it should be stored in mysql but its not getting stored can you please tell where i have done mistake here is my code.
Your query seems to be wrong.
Either use INSERT without WHERE if you want to insert a new record. If however you want to update an already present record, use UPDATE instead of INSERT.
And it is always a good idea to check whether a query was successful:
if (mysql_query ("insert into jcow_accounts(Time_Spent) values ('{$Time}') where uid='{$client['id']}' ") === FALSE) {
echo 'MySQL error: ' . mysql_error() . "\n";
}
You need to use an UPDATE instead of an insert.
$dtime = getChangeInTime(); // this is the change in time from the last update
mysql_query( "UPDATE jcow_accounts SET `TIME_SPENT` = `TIME_SPENT` + $dtime ".
" where id='{$client['id']}'" );
Try
insert INTO `jcow_accounts` (`Time_Spent`) VALUES ('{$Time}') where uid='{$client['id']}' WHERE `uid` = '{$client['id']}'
Are you sure the uid is in the DB? try running it without the WHERE...
Related
I am trying to code a user system. I am having an issue with the activation part. I can select and insert data to my table but now I am trying to create an update statement and got stuck.
<?PHP
include "db_settings.php";
$stmt = $dbcon->prepare("UPDATE 'Kullanicilar' SET 'Aktivasyon' = ? WHERE 'KullaniciID'=?");
// execute the query
$stmt->execute(array('1','5'));
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
?>
And I am getting error as:
"0 records UPDATED successfully".
This is my table; http://i.imgur.com/PL2eD80.png
I have tried by changing my 'Aktivasyon' type int to char but it also does not work.
EDIT:
I am trying to make this a function;
function dataUpdate($tableName, $updateRow, $updateValue, $conditonRow, $conditionValue)
{
include "db_settings.php";
$q = $dbcon->prepare("UPDATE $tableName SET $updateRow= ? WHERE $conditonRow= ?");
$q->execute(array($updateValue,$conditionValue));
}
I also try this :
...
$q = $dbcon->prepare("UPDATE `$tableName` SET `$updateRow`= ? WHERE `$conditonRow`= ?");
...
How can I make this statement work?
You are using wrong quotes. You are basically saying "update this table, set this string to something when the string KullaniciID equals the string 5" which of course never is true.
You should use backticks ` if you want to specify column names. Then your query would work. Usually you don't even need those, but for some reason MySQL world is always adding them.
So to clarify, this is a string: 'KullaniciID' and this is a column name: `KullaniciID`.
Also you should not send integers as strings. It causes extra conversions or even errors with more strict databases.
I have a query which is not inserting if i use the where clause, without the where clause it inserts data. this is weird and I have never seen it happen before in WAMP
$key=substr(md5(rand(0, 1000000)), 0, 5);
$key1="INSERT INTO login(key_id) VALUES('$key')
WHERE (email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')"
if(mysql_query($key1))
{
$message = 'User Added!.';
echo "<SCRIPT>
alert('$message');
location='forgotpassword.php';
</SCRIPT>";
}
If I echo $_POST['email_id'] it does return valid result
INSERT and WHERE do not mix.
when INSERTing, you are creating a new record.
WHERE is used with SELECTing DELETEing or UPDATEing, when you have to specify a filter which rows you want to SELECT, DELETE or UPDATE.
if you want to INSERT a row, do not use WHERE.
if you want to change a row, use
$key1="UPDATE login SET key_id = '$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
Insert is only used on creating new record and where clause is only used if want to set any condition it is used with like select,update,delete.
Try this it will help:-
$key1="update login set key_id ='$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
I know #Franz-Gleichmann is already explained very well, whats wrong in your code.
You need to use UPDATE for updating data modified code:
$key1 = "UPDATE login SET key_id = '$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";
Now i am adding two more points:
Please use mysqli_* or PDO, because mysql_* is deprecated and not available in PHP 7.
You missed the termination semi colon on the same line, i hope this is typo error.
I have never asked anything on one of these before, I could usually
think of or find a way that was posted for ideas.
I tried ways I thought of, tried using a CASE example that looked like it should work and no go. It won't update in any case.
OK here is what I am trying to do:
$Mysqlinfo="INSERT INTO `$PNum` (P_IDNum, P_Name, Raw_Time, Total_Time, T_Mode)
VALUES ('$PersId', '$_POST[PersonaName]', '$Stats_Vals[1]', '$Stats_Vals[2]', '$Stats_Vals[5]')
ON DUPLICATE KEY UPDATE Car_Model='$Stats_Vals[1]', Total_Time='$Stats_Vals[5]', Raw_Time='$Stats_Vals[7]', T_Mode='$Stats_Vals[2]' (there was originally the "; at end here)
***WHERE Raw_Time > '$Stats_Vals[7]'";***
(There were more names there but I removed some so it was not sooo loong, so don't mind so much the $Stats_Vals numbers as the structure).
The thing works without the WHERE at the end except it always will INSERT or UPDATE, I know Where does not work with ON DUPLICATE KEY unfortunately so what is an easy equivalent?
It has to chk for the Val and do NOTHING if the condition is NOT True.
Oh yeah it is formatted for use in a PHP script. :0)
Thanks much for any help!
Edit - Here is most of the PHP/sql code without the condition I am trying to achieve, it is called by an application:
<?php
hostname and
database info here
Variables, $_POST... etc.
$link = mysql_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysql_error());
}
else{
echo "Connection to Server successful!" . PHP_EOL; <for testing from web
}
$db_selected = mysql_select_db($database, $link);
if (!$db_selected) {
die ('Can\'t select database: ' . mysql_error());
}
else {
echo "Database successfully selected!". PHP_EOL;
$Mysqlinfo="INSERT INTO `$PNum` (P_IDNum, P_Name, Raw_Time, Total_Time, T_Mode)
VALUES ('$PersId', '$_POST[PersonaName]', '$Stats_Vals[1]', '$Stats_Vals[2]', '$Stats_Vals[5]')
ON DUPLICATE KEY UPDATE Car_Model='$Stats_Vals[1]', Total_Time='$Stats_Vals[5]', Raw_Time='$Stats_Vals[7]', T_Mode='$Stats_Vals[2]'";
if (!mysql_query($Mysqlinfo,$link))
{
mysql_close($link);
die('Error: ' . mysql_error());
}
}
mysql_close($link);
?>
it works except for not following the condition of only updating if Raw_Time is less.
Thanks again!
If you want to make the update conditional, then I'm afraid you can't do it with INSERT...ON DUPLICATE KEY UPDATE.... You'll have to do it in two or more queries. And in order to make it atomic, you'll have to use LOCK TABLES:
$primarykey = 'whatever';
query("LOCK TABLES mytable WRITE;");
$count = query("SELECT COUNT(*) FROM mytable WHERE id=?;", $primarykey);
if($count>0) // the ID already exists
{
$time = query("SELECT Raw_time FROM mytable WHERE id=?;", $primarykey);
if($time>$Stats_Vals[7])
query("UPDATE mytable SET ... WHERE id=?;", $primarykey);
}
else
query("INSERT INTO mytable ...");
query("UNLOCK TABLES;");
A couple of notes:
I'm calling some made up function query here because I don't know what method you're using to execute queries. I've also abbreviated some of the queries because I'm too lazy to copy all your code. You'll need to adjust the code according to your needs.
I've also used ? for parameters in the queries - this is good practice to prevent SQL injection.
The LOCK TABLES statement is there to ensure that no other process can delete the record you're working with between the time you check for the record's existence (SELECT COUNT(*)...) and the time you update. If that were to happen, your code will cause an error.
There is no single-query solution, you either have to retrieve the value of the Raw_Time column for the appropriate record (if exists) and evaluate that in your PHP script; or create a stored procedure for the task.
By the way, look out for security issues, like SQL Injection, when inserting values in your query given by the users.
I want to run multiple mysql queries from one php page but I need it to "wait" until each query is finished before moving on. It seems that at the moment it will load them all at the same time.
Is there a work around for this or a function to make the page wait until the query is done before going to the next one?
--edited--
so here is my code
//These top three seem to work fine but I guess it doesn't matter if the next one starts before the last one ends
mysqli_query($con,"DELETE\n".
"FROM\n".
" temp_cats");
mysqli_query($con,"DELETE\n".
"FROM\n".
" temp_concats");
mysqli_query($con,"DELETE\n".
"FROM\n".
" temp_locations");
That seems to work OK but I wouldn't notice if one starts before the one before ends.
The next query works fine. It takes countrys mentioned in the query from another table and adds it to a new table. The update query "labels" them in another column.
mysqli_query($con,"INSERT IGNORE temp_locations (temp_locations.Location) SELECT DISTINCT\n".
"Region\n".
"FROM\n".
"LocationsForExcel\n".
"WHERE\n".
"Country IN (" . $_SESSION['SearchCountriesQuery'] . ")");
//mark the new locations type as country
mysqli_query($con,"UPDATE temp_locations\n".
"SET LocationType = 'Country'\n".
"WHERE\n".
" LocationType IS NULL");
The problems come when I put this underneath:
mysqli_query($con,"INSERT IGNORE temp_locations (temp_locations.Location) SELECT DISTINCT\n".
"Region\n".
"FROM\n".
"LocationsForExcel\n".
"WHERE\n".
"Country IN" . $_SESSION['SearchCountriesQuery'] . ")");
//mark the new locations type as region
mysqli_query($con,"UPDATE temp_locations\n".
"SET LocationType = 'Region'\n".
"WHERE\n".
" LocationType IS NULL");
The end result is that both of the INSERT queries are running fine but the 'LocationType' column are all showing as 'Country'.
The only thing that I can think is happening is that the queries are not running in order or are over lapping each other.
Does anyone see whats going on here?
This is not a realy good method of doing it but what you could to is this (Showing some code would help a lot):
<?php
$query = //your query
if($query) {
$query2 = //your 2nd query
}
if($query2) {
$query3 = //your 3rd query
}
//and so on
?>
Hey I am currently trying to insert a global variable to a table. The other values I pass are variables too but they get sent correctly.
Here is my query. my error handling does not capture anything
$result = mysql_query("INSERT INTO IPmanagement (userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES ('" .$masterUserId . "', '" . $Entry['LeadName'] . "', '" . $Entry['LeadEmail'] . "', '0', '" . $ip . "')") or die(ErrorException("Function 6", "Error when processing the current lead. your data is unaffected and if the proccess continues please contact an Admin.", mysql_error(),$_SERVER['REMOTE_ADDR'], CurrentPath(), $masterUserId));
my variable that is global defined before the function is
$masterUserId = "1";
I tried echoing the variable before it sends and it echos out correctly YET my table holds a value of 0.
here is a screenshot of how I have my table setup.
Click for Larger Image
Any idea what is going on. I am rather stumped and tried writing this same code different ways and it still gives me same issue. Also $masterUserId will always be an int value
Edit: also would like to mention the variable is different .php that contains the varaiable and database login information. It is being included at the top. (don't know if that is relevant)
Because you are not inserting IP STATUS.Which is not null
\
You should either set this to null or enter some value to it.
If you are using query in a function than use like this
function (){
//than define
$globat $masterUserId;
// use the global defination
// than use this variable with global value
}
Do not use mysql_*. Replace them with mysqli_* or PDO::.
Did you try to echo the mysql_query()? Do this. Replace mysql_query("..."); with die("..."); and put it in the phpMyAdmin and try executing.
And in your table, I see that IP Status is a NOT NULL. So that might throw an exception. Use a default value in the table.
And yeah, what do you get the result as in mysql_error()?
Why ''' or "' in query?
I have cleaned up query with PHP function sprintf and using NULL for EntryID(Autoincrement)
$query = sprintf("INSERT INTO IPmanagement (EntryID,userId, NameUsed, EmailUsed, IPStatus, Ip) VALUES (NULL,%s,%s,%s,'0',%s)",
$masterUserId , $Entry['LeadName'] , $Entry['LeadEmail'] , $ip ));
$result = mysql_query($query);
You should also use MySQLi or PDO