copying data from table to table: validate mysql query - php

How would I go about validating this query? Currently, I getting some omissions where one row hasn't copied over so I need a bombproof method to check and correct. Query:
$query = "
SELECT *
FROM $UID
";
$result = mysql_query($query)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$q = $row['QID'];
$a = $row['answer'];
$c = $row['comment'];
$query = "
INSERT INTO a (UID, QID, answer, comment)
VALUES ('$UID', '$q', '$a', '$c')
";
mysql_query ($query)or die(mysql_error());
}
Thanks.

You can do this in a single query.
INSERT INTO a (UID, QID, answer, comment)
SELECT '$UID', QID, answer, comment FROM `$UID`
As its an atomic operation all the data will be copied in one shot. However you can still verify by using mysql_info function. It'll give output like following.
Records: 23 Duplicates: 0 Warnings: 0
Here Duplicate is the number of rows there were discarded due to duplicate key. If both Duplicates and Warning are 0 you can say query was successful.

Related

MySQL query mishandling date field

I've got a PHP/MySQL script that is yielding strange results on a date field. All along the process, my dates are fine until the very end. The final result has every entry in the date field as '0000-00-00'. I'm totally stuck and don't know what else to do. I can tell that this is an issue with PHP not interpreting this as a date, but I don't know how to fix it. Here is my code:
$sql = "CREATE TABLE temp_workouts (my_date date, sg_id int(11), loc_id int(11))";
$result = mysql_query($sql);
if (!$result) {
$tag_success = "failure";
$tag_message = mysql_error();
echo encodeJSON($tag_success, $tag_message);
die();
}
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
die();
When I flip over to MyPHPAdmin and look at the table, the entire column my_date contains '0000-00-00'. How can I get PHP to recognize this as a 'Y-m-d' formatted date? Thanks. I appreciate any help.
I suspect the issue is that you haven't enclosed a string literal in single quotes:
INSERT INTO temp_table (my_date) VALUES ('$my_date')
^--- ^--- string literals in single quotes
Otherwise, the statement is probably something like:
... VALUES (2013-08-22)
MySQL isn't converting that into a valid date, issuing a warning message, and inserting a "zero" date.
Your immediate problem is that you don't use quotes around date values in your insert statement.
Change
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
to
$sql = "INSERT INTO temp_table (my_date) VALUES ('$my_date')";
^ ^
Now, you can just use INSERT ... SELECT syntax to achieve your goal in one go
INSERT INTO temp_table (my_date)
SELECT my_date
FROM my_table
Therefore this part of your code
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$my_date = $row['my_date'];
echo $my_date . " "; //<--this output looks perfect
$sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
$result2 = mysql_query($sql);
}
can be changed to
$sql = "INSERT INTO temp_table (my_date)
SELECT my_date FROM my_table";
$result2 = mysql_query($sql);
On a side note: Consider switching to either PDO or MySQLi and use prepared statements.
Try this one...This will re-convert it to date, and then save..
$dt = strtotime($row['my_date']);
$date = date("Y-m-d",$dt);
$sql = "INSERT INTO temp_table (my_date) VALUES ({$date})";

PHP insert into database query

I am trying to insert values into a database table, a row is inserted but blank no values are inserted. Only the order_id which is the primary key with auto increment increase.
php code:
<?php
$user_get = mysql_query("SELECT * FROM users");
while($row_user = mysql_fetch_assoc($user_get)){
if($row_user['username'] == $_SESSION['username']){
$row_user['first_name'] = $res1;
$row_user['last_name'] = $res2;
$store_order ="INSERT INTO oko (user, product) VALUES ('$res1', '$res2')";
mysql_query($store_order);
}
}
?>
Your assignments are backwards. I think you meant to:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
Don't you mean:
$res1 = $row_user['first_name'];
$res2 = $row_user['last_name'];
You could also update the SELECT to have a WHERE clause that checks $_SESSION['username'].
You could also just do an INSERT/SELECT:
INSERT INTO oko (user, product)
SELECT
first_name, last_name
FROM
users
WHERE
username = '$_SESSION["username"]'
Your code is vulnerable to injection. You should use properly parameterized queries with PDO/mysqli

Problem with syntax error

Hi guys am fighting with a syntax error of my sql, saying exactly:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax"
Even though the code is working and doing what I wanted I still get the syntax error info!
and here is the code:
$person_id =mysql_query("SELECT person_id FROM person WHERE firstname='$array[0]' AND lastname='$array[1]' AND city='$array[2]' ")
or die(mysql_error());
if (mysql_num_rows($person_id) )
{
print 'user is already in table';
}
else
{
mysql_query ("INSERT INTO person VALUES (NULL, '$array[0]' ,'$array[1]' , '$array[2]' ")
or die(mysql_error());
$person_id = mysql_insert_id();
}
$address_id =mysql_query("SELECT address_id FROM address WHERE street='$array[3]' AND city='$array[4]' AND region='$array[5]'")
or die(mysql_error());
if (mysql_num_rows($address_id) )
{
print ' already in table';
}
else
{
mysql_query ("INSERT INTO address VALUES (NULL, '$array[3]', '$array[4]', '$array[5]'")
or die(mysql_error());
$address_id = mysql_insert_id();
}
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)")
or die(mysql_error());
Thanks for any suggestions
It's probably because you haven't escaped your values...
Try:
$query = "SELECT age FROM person WHERE name='".mysql_real_escape_string($array[0])."' AND lastname='".mysql_real_escape_string($array[1])."' AND city='".mysql_real_escape_string($array[2])."'";
And read up on SQL injection.
EDIT
I think your problem is that you are trying to pass mysql result resources directly into a string, without fetching the actual values first.
Try this:
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the person already exists in the database, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]')";
mysql_query($query) or die(mysql_error());
$person_id = mysql_insert_id();
}
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// INSERT a record linking person and address
mysql_query ("INSERT INTO person_address VALUES($person_id, $address_id)") or die(mysql_error());
ANOTHER EDIT
Firstly, I have modified the code above - added a couple of comments, corrected a couple of small errors where the wrong variable was referenced and re-spaced it to make it more readable.
Secondly...
You are getting that additional error because you are trying to insert a new row into your person_address table, which doesn't seem to have a sensibly configured primary key. The easy work around to the problem you currently have is to run a SELECT against this table to see if you have already got a record for that user, then if you have you can do an UPDATE instead of the INSERT to alter the existing record.
However, if I understand what your doing here correctly, you don't actually need the person_address table, you just need to add another integer column to the person table to hold the ID of the corresponding row in the address table. Doing this would make many of your future queries potentially much simpler and more efficient as it will be much easier to SELECT data from both tables at once (you could do it with your current structure but it would be much more confusing and inefficient).
The following code example could be used if you add another integer column on the end of your person, and call that column address_id. You will notice it's very similar to the above, but there are two key differences:
We do the address stuff first, since we will keep track of the relation in the person record
We do an UPDATE only if we find a person, otherwise we just INSERT a new person as before
// Create an array of escaped values to use with DB queries
$escapedArray = array();
foreach ($array as $k => $v) $escapedArray[$k] = mysql_real_escape_string($v);
// See if the address already exists in the database, INSERT if not
$query = "SELECT address_id FROM address WHERE street='$escapedArray[3]' AND city='$escapedArray[4]' AND region='$escapedArray[5]'";
$address = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($address) ) {
print 'address already in table';
$address = mysql_fetch_assoc($address);
$address_id = $person['address_id'];
} else {
$query = "INSERT INTO address VALUES (NULL, '$escapedArray[3]', '$escapedArray[4]', '$escapedArray[5]')";
mysql_query ($query) or die(mysql_error());
$address_id = mysql_insert_id();
}
// See if the person already exists in the database, UPDATE if he does, INSERT if not
$query = "SELECT person_id FROM person WHERE firstname='$escapedArray[0]' AND lastname='$escapedArray[1]' AND city='$escapedArray[2]' LIMIT 1";
$person = mysql_query($query) or die(mysql_error());
if ( mysql_num_rows($person) ) {
print 'user is already in table';
$person = mysql_fetch_assoc($person);
$person_id = $person['person_id'];
$query = "UPDATE person SET address_id = '$address_id' WHERE person_id = '$person_id'";
mysql_query($query) or die(mysql_error());
} else {
$query = "INSERT INTO person VALUES (NULL, '$escapedArray[0]', '$escapedArray[1]', '$escapedArray[2]', '$address_id')";
mysql_query($query) or die(mysql_error());
}
If we structure the database in this way, it allows us to do this:
SELECT person.*, address.* FROM person, address WHERE person.address_id = address.address_id AND [some other set of conditions]
Which will return the person record, and the address record, in the same result set, all nicely matched up for you by the database.
YET ANOTHER EDIT
You need to add an auto-increment primary key to the person_address table, and perform a SELECT on it to make sure you are not adding duplicate records.
You should replace the final INSERT statement with the following code segment. This code assumes that you have a primary key in the person_address table called relation_id. It also assumes that the id field names in this table are named in the same way as they are in the other two tables.
// See if a relation record already exists for this user
// If it does, UPDATE it if the address is different
// If it doesn't, INSERT an new relation record
$query = "SELECT relation_id, address_id FROM person_address WHERE person_id = '$person_id' LIMIT 1";
$relation = mysql_query($query);
if ( mysql_num_rows($relation) ) {
$relation = mysql_fetch_assoc($relation);
if ($relation['address_id'] == $address_id) {
print 'The record is identical to an existing record and was not changed';
} else {
$relation_id = $relation['relation_id'];
$query = "UPDATE person_address SET address_id = '$address_id' WHERE relation_id = '$relation_id'";
mysql_query($query) or die(mysql_error());
}
} else {
$query = "INSERT INTO person_address VALUES(NULL, '$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
EVEN MORE EDITING
Try this to replace the code from above:
// See if a relation record already exists for this user
// If it doesn't, INSERT an new relation record
$query = "SELECT person_id FROM person_address WHERE person_id = '$person_id' AND address_id = '$address_id' LIMIT 1";
$relation = mysql_query($query);
if ( !mysql_num_rows($relation) ) {
$query = "INSERT INTO person_address VALUES('$person_id', '$address_id')";
mysql_query($query) or die(mysql_error());
}
You cannot use array values like that inside of quotes - instead you could, for example, separate the values from the query using dots.
$query = "SELECT age FROM person WHERE name='".$array[0]."' AND lastname='".$array[1]."' AND city='".$array[2]."'";
the second and fourth query do not have an ending ')' at the end of the values

help with multiple queries (PHP/MySQL)

PLease note I am a beginner.
My situation is thus:
I am trying to run multiple queries, off the back of a dynamic form. So the data is going to end up in two different tables.
I am currently successfully storing in to my item_bank, which has an auto_increment itemId.
I then want to grab the ItemId just created on that last query and insert it into my next query of which I am also inserting an array. (I hope you can follow this)
first off, is it even possible for me to run multiple queries like this on a single page?
Below is my attempt at the queries. Currently the first query works, however I cannot get the ItemId generated from that query.
$answers is an array.
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$query = "INSERT INTO answers_tb (item_id, text_value)VALUES('$itemid',' . implode(',', $answers) . ')";
mysql_query($query) or die(mysql_error());
this is the error i get now: "Column count doesn't match value count at row 1"
To get the ID generated by an auto-increment field in PHP/MySQL just use the mysql_insert_id() function.
Edit:
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$answers = mysql_real_escape_string(implode(',', $answers));
$query = "INSERT INTO answers_tb (item_id, text_value) VALUES('$itemid','$answers')";
mysql_query($query) or die(mysql_error());
Have a look at mysql_insert_id():
// store item structure info into item_bank_tb
mysql_query($query);
$itemid = mysql_insert_id();
// now store different answers

Get a column value (like id) after mysql INSERT

Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.

Categories