I'm trying to execute 2 queries, but whenever I follow the guides online about multi queries, its not doing either of the queries.
What I'm trying to do on the first query is to INSERT or ADD whatever the user inputs on $HISTORY on the record that's currently on colHistory; I.E.:
Current data on colHistory:
A
User inputs 'B' on $HISTORY, the syntax should add 'B' on the 'A' that's currently on record, or 'AB'. Then use the second query to UPDATE all the other records or columns on this particular row.
Here's the code (Please note that the '...' means more code that's unnecessary):
$query = INSERT INTO tbInventory SET colHistory='$HISTORY' WHERE colSerno='$SERIALNUM';";
$query .= "UPDATE tbInventory SET
colImage='$IMAGE',
colSerno='$SERIALNUM',
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
mysqli_multi_query($con,$query);
Please note where I declared colHistory as '' before I insert the data from the form. I'm not sure if I'm doing it right on this part. Is there anything that I'm missing?
*Edit:
I have already tried executing the queries one by one as:
mysqli_query($con,"INSERT INTO tbInventory SET colHistory='$HISTORY' ");
mysqli_query($con,"UPDATE tbInventory SET
...
...
colHistory=''
WHERE colSerno='$SERIALNUM'";
Yet it doesn't seem to work either, the whole thing gets ignored.
(** I have a script below the code block above where I could print the results already, and it does run)
Well I can tell you why your first query is broken.
INSERT INTO tbInventory SET colHistory='$HISTORY'
This query is using UPDATE syntax but you are telling the query processor to expect INSERT INTO syntax. So the query is unable to execute.
Decide whether you are needing to UPDATE an existing record or INSERT a new one and alter your query to reflect that. (Change INSERT INTO to UPDATE or change "Set colHistory = '$ History'" to "Values ('$ History', 'col2Val', and so on..")
As for your second query, the syntax looks alright from what you have shown but since you didn't post the entire query its hard to say what is happening there. If you can show more of that query I can update this response.
Here's a good SO question on inserts vs updates.
What are differences between INSERT and UPDATE in MySQL?
I ended up dropping the multi-query method and I did got my intended results by somehow cheating:
I assigned the old data or the data that's currently on the colHistory cell, displayed it, but I disabled the textarea. I then created one more hidden textbox in the script with the old data in it and then hid it to the users view.
I then concatenated both textareas with the new one that I've created that the user could modify, emulating the results wanted.
Related
Side Note: First off, I would like to say that I am not an experienced web developer, so anything in the code I've included that you see can be improved or done better please let me know, as I am always looking to improve and learn from those with more experience and knowledge than myself.
I am creating a form wizard type website, where the user advances through various forms and fills out information. At the end of the information gathering, I write the collected data to a MySQL database running on WAMP. The data that I am writing is going to multiple different tables within the database. There will always be 3 separate INSERT queries, but up to about 15 depending on the data the user inputs ( each query corresponding to a different table). The problem that I am having is that, if any of the INSERT statements have an error it will not write to that table (good), but it will write to all the other tables (of course).
What I would like to be able to do is only write all the data if none of the queries have errors. If any of the queries have errors and will not write to their respective table, I would like to not write any data and present an error message to the user.
The only way that I have been able to come up with to accomplish this so far, is to write to the tables using a PDO statement object and on $pdostmt->execute() catch if it returns false. Then when a failure (false) is encountered, retroactively go back and delete any records that have already been written. This does not seem to be a good way to go about it, and I'm thinking somewhere out there someone can point me to a better way, but I haven't been able to find that way yet.
Example of 2 INSERT queries below:
$revisionUpdate = "INSERT INTO revision_history (stock_number, revision_date)"
." VALUES ('"
.$dataLocation['stocknumber.tpl']['stocknum']."','" //stock_number
.$timestamp //revision_date
."')";
$updatestatement = $db_config_data->prepare($revisionUpdate);
// Execute the query to update table
$updatestatement->execute();
$infoUpdate = "INSERT INTO info (stock_number, revision_date, engineer, customer_name, model,"
."above_one_gigabyte, installed_os, network_location, mac_dupe_check,"
."time_local_tz, time_local_dst, time_offset, time_dst, configurator_version, stephen)"
." VALUES ('"
.$dataLocation['stocknumber.tpl']['stocknum']."','" //stock_number
.$timestamp."','" //revision_date
.$dataLocation['general.tpl']['engineer']."','" //engineer
.$dataLocation['general.tpl']['company_name']."','" //customer_name
.$dataLocation['general.tpl']['parent_pn']."'," //model
.(int)($dataLocation['preflight.tpl']['tot_sys_memory'] == '1gb_greater').",'" //above_one_gigabyte
.$dataLocation['preflight.tpl']['installed_os']."','" //installed_os
.$dataLocation['general.tpl']['network_location']."'," //network_location
.(int)!array_key_exists('skip_MAC', $dataLocation['pxeactions.tpl']).",'" //mac_dupe_check
.$dataLocation['timezone.tpl']['timezone']."'," //time_local_tz
.(int)array_key_exists('dst_adjust', $dataLocation['timezone.tpl']).",'" //time_local_dst
.$dataLocation['timezone.tpl']['timezone']."'," //time_offset
.(int)array_key_exists('dst_adjust', $dataLocation['timezone.tpl']).",'" //time_dst
."1.0'" //configurator_version
.")";
$updatestatement = $db_config_data->prepare($infoUpdate);
//Example of how I'd catch the failed INSERT query
if ( !($updatestatement->execute()) )
{
print_r($updatestatement->errorInfo());
}
So in the example above if $revisionUpdate succeeded and $infoUpdate failed, I would like to have none of the $revisionUpdate data written to the database, and same goes for any other queries that came before $infoUpdate.
Thanks for any help.
i have a table that must by update every month, due i upload text file on server and save it in temporary table, the bellow code show it:
$result_emp = "LOAD DATA LOCAL INFILE'".$myFile_emp."' INTO TABLE infemptemp COLUMNS TERMINATED BY ','";
then after update successfully and insert new data in "infemptem" table, i should compare the data of main table's "infemp" that have old data by "infemptemp" that have new data, for do this Scenario i write bellow code:
$viwe_emp =mysqli_query($conn,"select * from infempsame where 1");
$NumRows_emp=mysqli_num_rows($viwe_emp);
//echo $NumRows_vam;
$i=0;
while(($row=$viwe_emp->fetch_assoc())!=NULL)
{
$prsid1=$row['PrsID'];
$AccID1=$row['AccID'];
$numid1=$row['NumID'];
$sql2="select * from infempsame where prsID='".$prsid1."';";
if (mysqli_query($conn,$sql2))
{
$sql2_update="UPDATE `infemp` SET AccID='".$AccID1."',NumID='".$numid1."' WHERE prsID='".$prsid1."';";
if(mysqli_query($conn,$sql2_update))
{
$i+=1;
}
}// end if (mysqli_query($conn,$sql2))
}// end while insert new fields of infvam
by attention to the code and have 3500 record in "infempsame " table on my database, when i want update "infemp" table, the time out on browser occur.
I think if write above code by procedure, my problem solved.
Is it true? How do i can write procedure and call or use it?
Best Regards.
A stored procedure would be overkill. There is a better way hidden away but it get's only a very brief mention in the manual
You can also perform UPDATE operations covering multiple tables.
However, you cannot use ORDER BY or LIMIT with a multiple-table
UPDATE. The table_references clause lists the tables involved in the
join. Its syntax is described in Section 13.2.9.2, “JOIN Syntax”. Here
is an example:
UPDATE items,month SET items.price=month.price WHERE
items.id=month.id;
Thus you can write a simple query to get rid of the PHP script like this.
UPDATE infemp, infemptemp
SET infemp.AccID=infemptemp.AccID,
infemp.NumID=infemptemp.numID
WHERE infemp.prsID=infemptemp.prsID;
if you have an index on the prsID column this should complete very quickly.
I trying to add +1 in a column after select but its not working, what I want is, when I make a search, the scripts adds +1 in a column to track how much searches I did.
Heres how it is now
$QUERY = "SELECT company FROM test WHERE number = '$number[0]' LIMIT 1";
And I want to add this
UPDATE users SET consultas=consultas+1 WHERE username = '$username'
If I add another $QUERY line the script breaks, any ideas ?
By nature, SELECT queries are for returning information from the database, not updating the database. To this end, triggers aren't even available for SELECT queries to react to the action. As such, if you want to increment a value, this must be done in a separate query, as an UPDATE query or possibly an INSERT ... ON DUPLICATE KEY UPDATE query if that better suits your needs.
You should execute those as two separate queries. Also, be very careful to ensure your data is properly escaped because it looks like you've forgotten to do that.
Be sure to check the result code of each as an error may occur at any time. If you use PDO there's a fairly robust error handling pattern you can follow.
I am doing some PostGIS work on a CakePHP application.
Because I've been working with some database functions, I've done raw $this->query() calls to do inserts of data. I'm at a point where I need to get the ID of the result of an insert query, but $this->query() returns an empty array.
Here is the query I'm using for inserts:
INSERT INTO locations (title,company_id,state_id,poly,point)
VALUES ('$title',$company_id,$state_id,ST_GeomFromText('$geom',4269),$point);
The problem is Cake is trying to insert 'ST_GeomFromText('$geom',4269)' as a string, and I cannot figure out how to get it to remove the quotes in the SQL insert statement it prepares via $this->Location->save();.
Any suggestions?
Edit:
Before I was doing $this->query(); and my SQL works fine. That's not the issue.
Now when I do:
$this->Location->create();
$this->Location->set('poly',$poly);
... Set all the rest of the model fields ...
$this->Location->save();
The SQL that gets produced looks like this:
INSERT INTO locations (title,company_id,state_id,poly,point)
VALUES ('Some Title',5,23,'ST_GeomFromText('$geom',4269)',POINT(-72.342,102.23455);
Because ST_GeomFromText gets 'quoted', PostgreSQL throws an error and doesn't insert the geometry.
The solution to my problem turned out to NOT be a CakePHP based one, but a PostgreSQL one!
By appending "RETURNING id" to the query like this:
INSERT INTO locations (title,company_id,state_id,poly,point)
VALUES ('$title',$company_id,$state_id,ST_GeomFromText('$geom',4269),$point) RETURNING id;
The query no longer returns an empty array, and now returns the ID of the row it just created!
Via $this->ModelName->getLastInsertID(); you are able to get the last inserted ID. So, after a save you can call this code to get its id.
I am trying to build a dynamic set of comboboxes/listMenus getting data from a MySQL DB. My database has 5 fields, 1st being id and
topic, sub_topic, info and url
I want to make it so that until user selects a valid choice from box1 that the others are disabled. Once user selects from box 1 box 2 will be activated. Once you make a selection from box 2 then the info and url will be shown.
I have followed a tutorial http://www.ssdtutorials.com/tutorials/series/dependable-dropdown.html and so most of this code is not mine apart from the SELECT statements
I am having problems writing the MySQL for update.php as this populates the other boxes (currently I am sticking with the comboboxes until I have it working.)
I would be grateful for some help, due to the amount of code it can be seen here http://pastebin.com/QNbHR9JK
Thanks in advance.
The first thing I see is that in update.php query, you aren't actually using a where clause. When you execute the prepared query, you pass in a value array, but there aren't any placeholders in the prepared query.
I would expect something like:
$sql = "SELECT `topic`,`sub_topic`,`info`,`url`
FROM `links` WHERE sub_topic=?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
One other thing I notice is that in your foreach in update.php, you are using $row['id'] but you aren't selecting that column in your query.
EDIT
I updated the query to use the proper column in where clause, and removed to group by clause based on discussion.