I'm looking to enter in a whole object of information. The data itself needs to be put into different tables so I'm using a mysqli_multi_query
Query
for($i=0;$i<$commLength;$i++){
$sql = "INSERT INTO
calinfo (Sbefore, Safter, A1, A2, CalGas, Factor, Zbefore, Zafter, Cbefore, Cafter, SysInfoID)
VALUES
('{$comm[$i]->ScB4}', '{$comm[$i]->ScA4}', '{$comm[$i]->A1}', '{$comm[$i]->A2}', '{$comm[$i]->CalGasA}', '{$comm[$i]->Factor}', '{$comm[$i]->ZB4}', '{$comm[$i]->ZA4}', '{$comm[$i]->CalB4}', '{$comm[$i]->CalA4}', '{$comm[$i]->CHNoID}');";
$sql .= "UPDATE
jobs
SET
CompletedBy = $tech
WHERE JobID = '{$comm[$i]->JobID}';";
if(!mysqli_multi_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
$synctotal++;
}
}
I think I'm doing this wrong. All the data and values and being read correctly but I get this error code:
'Error: Commands out of sync; you can't run this command now'
Could someone point me in the right direction with this one please =)
Did you try running two sql queries as separate statements? rather than keeping them in 1 SQL string variable?
Related
I am having an issue with this not running at all when the information is submitted, I believe that I have the syntax wrong.
if ($_POST['note'] != $player->note_text) {
$message = 'Admin '.$user.' has added the note ('.$_POST['note'].') to '.$player->name.'('.$pid.')';
logIt($user, $message, $dbcon);
$note = $_POST['note'];
$note = '"'.$note.'"';
$UpdateN = "INSERT INTO notes (uid, staff_name, name, alias, note_text, warning) VALUES ('$_POST[hidden]', '$user', '$player->name', '$player->aliases', '$note','$_POST[warn]')";
$UpdateN2 = "INSERT INTO players WHERE `playerid` = $_POST[hidden] (warning) VALUES ('$_POST[warn]')";
mysqli_query($dbcon, $UpdateN, $UpdateN2);
The new line I added which seems to have broken it is '$UpdateN2'.
I am not sure if the new line has broken the statement, since I am new to PHP and mysqli any pointers to forums or websites that I can learn and understand this in a more detailed way I would appreciate.
Edit: I have since moved from using mysqli to PDO, I strongly suggestion that anyone willing to start using MYSQL commands with PHP to have a look at this: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
I started reading this and testing things out, I find this much more easier but also it looks a lot cleaner and understandable when reading it back after a few days have passed.
In keeping with the mysqli procedural style in the original, using prepared statements with bind placeholders, something like this:
$UpdateN = 'INSERT INTO notes (uid, staff_name, name, alias, note_text, warning)'
. ' VALUES ( ?, ? , ? , ? , ? , ? )';
$UpdateN2 = 'UPDATE players SET warning = ? WHERE playerid = ? ';
if( $sth = mysqli_prepare($dbcon,$UpdateN) ) {
mysqli_stmt_bind_param($sth,'ssssss'
,$_POST['hidden']
,$user
,$player->name
,$player->aliases
,$_POST['note']
,$_POST['warn']
);
if( mysqli_stmt_execute($sth) ) {
// statement execution successful
} else {
printf("Error: %s\n",mysqli_stmt_error($sth));
}
} else {
printf("Error: %s\n",mysqli_error($dbcon));
}
if( $sth2 = mysqli_prepare($dbcon,$UpdateN2) ) {
mysqli_stmt_bind_param($sth2,'ss'
,$_POST['warn']
,$_POST['hidden']
);
if( mysqli_stmt_execute($sth2) ) {
// statement execution successful
} else {
printf("Error: %s\n",mysqli_stmt_error($sth2));
}
} else {
printf("Error: %s\n",mysqli_error($dbcon));
}
If it was me, I'd just make two separate calls to mysqli_query, one for each of your separate queries. PHP has historically been very wary of permitting multiple queries in a single function call, because of possible sql injection vulnerabilities.
On a related note, you need to sanitize your input. $_POST should never, ever, ever appear directly in a mysql query string, because your post data might -actually be something like ')"; DROP TABLE users;'.
Finally, you're using a WHERE clause on an insert. That's probably breaking your query. You should take a couple of days and research how and why that's breaking your query, and how and why to write proper sql queries. Doing so will add value to your company, because your company is less likely to suffer a catastrophic data breach, and it will add value to you, because you'll be a better SQL coder.
Edit: and in the time it took me to write this, three different people made each of those points. LOL.
Im working with sql database (phpMyadmin) and with programming language PHP.
I've got a table with data e.g:
T1:
145
138.8
110.6
1759.4
1400.9
1891.4
1755.4
1760.4
T2:
141.9
110.6
1400.9
1891.4
1758.4
My question >
Is there existing sql syntax, that is able to average values which are lying in ONE THRESHOLD (like > 1755.4,1760.4,1759.4 OR 145,138.8) and INSERT THEM AS UNIQUE VALUES to another table ?
What I need is create T2(contain UNIQUE values) from T1, and INSERTING them only if they didn't exist in T2.
I was trying, to looping throw 2 arrays (1starray = T1 and 2ndarray = T2 ) too. And compare data in array1 and array2, and trying to insert values which can be unique.
for($z = 0; $z<$numberApp; $z++) {
while($j<$numberAbs-1){
$Abs=$arrayabs[$j];
$state_change = (abs($Abs - abs($previous_Abs)));
if ($state_change>100){
$instantChange = True;
echo "<br>"." better than tolerance: " . $instantChange;
}
else {
$instantChange = False;
echo "<br>"." lower than tolerance" . $instantChange;
}
//if($state_change = (abs($some_item - $previous_item)<= $tolerance)){
if($Abs != $previous_Abs){
echo "<br>" ." some_item : " .$Abs." previous_item : " .$previous_Abs;
}
//$lastAbs=$arrayabs[$j];
//echo " next_item : " .$lastAbs;
if ($instantChange == True and $onChange == False){
$Abs2 [] = $podiel;
$finalPower = $podiel;
}
if ($instantChange){
$D=0;
echo "ABSOLUT >>> " .$lastAbs;
$percentual1 = ($power_app[$z] * 0.9);
$percentual2 = ($power_app[$z] * 1.1);
if(($lastAbs<$percentual1 || $lastAbs>$percentual2)){
$user = 'root';
$pass = 'password';
$db = 'vypis';
//if($N>0){
$db = new mysqli('localhost', $user, $pass, $db) or die();
$sql = "INSERT INTO vypis.nilm_app2(power) VALUES ('$lastAbs')";
if(mysqli_query($db, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
}
//$power_app[$z++];
}
Thank you for everyone, who going to help, and sorry for my bad english.
The math here sounds complex enough that you're probably better off doing the complex stuff (averaging the values and determining whether a value is unique) in PHP, then finishing off with a couple simple MySQL statements.
This can probably be done in pure MySQL with a bit of trickery, but frequently it isn't worth the time and complexity it creates. (Imagine you'll have to debug that monster SQL query six months from now!)
By contrast, it's trivial to take a handful of values in PHP and average them; it's also trivial to run a quick MySQL query to determine whether a value is unique. So if you're unsure how to mash these together into one big SQL statement, start out by just handling them in the PHP code as separate steps! Then later on, if performance issues come up, you can think about how to combine them (but at least by that point you already have something that works).
$query = "START TRANSACTION;\n".$update.$insert."COMMIT;\n";
//print $query;
if (!$mysqli->multi_query($query)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
// need to delay somehow until after the transaction is complete.
header('Location: ../seller-services.php?services=$'.$services);
The problem I am having is when I call the seller-services.php the changes just made by the transaction are not reflected in the database yet, so the queries I use to generate the output for seller-services.php aren't necessarily visible. If I hit refresh I will see the changes. I could do some type of hard delay, like a second, but I would rather synchronize the php execution to the mysql transaction. If that is possible please let me know.
I don't think the type of query is important but in case you would like to see part of this query in more concrete form:
Inside a loop I:
$insert .= "
INSERT INTO SellerServices
(`id`, `Type`, `Details`, `Active`)
VALUES
('$id', '$type', '$details', '1')
ON DUPLICATE KEY UPDATE
`Details`='$details',
`Active`='1';\n";
$services .= "&$type";
I think you can use your imagination for the rest
You just need to loop through each query, even if you don't do anything:
while ($mysqli->next_result()) {}
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 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...