insert sql statement into mysql database like common string? - php

I wrote a logger function and it inserts "insert and update queries" to database. altough I apply "mysql_real_escape_string" to the sql stament, I cannot insert it to the database.
any suggestion please?

INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1 UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1)
In SQL, strings must be quoted. You are also missing a comma. Try this:
INSERT INTO kayit (ip, user_id, query) VALUES ('127.0.0.1', 1, 'UPDATE faal_ekonkod SET bedel = 12000 WHERE id = 1')

i have also problems with this function, then i use the addslashes() function, its not an answer but a solution.
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));

Related

is it possible to execute 2 query at the same time?

hey guys i have this problem..
basicly the first query is jsut for inserting and the 2nd query is for copying data from another table via foreign key. have any idea? im newbie.. :D
else if($payment_description == 'Monthly Subscription'){
$payment_amount = '750';
$sql = "INSERT INTO `paymentlog` ( payment_amount,payment_description,date_payment)
VALUES ( '$payment_amount', '$payment_description','$date_payment')";
$query_run = mysqli_query($conn, $sql);
$sql1 = "INSERT INTO paymentlog (member_id, first_name, last_name)
SELECT member_id, first_name, last_name
FROM member
WHERE member_id = $id";
$query_run1 = mysqli_query($conn, $sql1);
echo ("<script LANGUAGE='JavaScript'>
window.alert('Monthly Payment is been added.');
window.location.href='/PROJECT/MEMBERS/members.php';
</script>");}
I don't think your current code does what you want. You are (attempting to) insert two rows, while, as I understand your question, you want to create a single row in payment_log, with the amount, description and date given as input, and member information that needs to be retrieved from another table using another input paramter.
You can use the insert ... select syntax:
INSERT INTO `paymentlog` (
member_id,
first_name,
last_name,
payment_amount,
payment_description,
date_payment
)
SELECT
member_id,
first_name,
last_name,
:payment_amount,
:payment_description,
:date_payment
FROM member
WHERE member_id = :id
Important notes:
Use prepared statements! Do not concatenate variables in the query string, this is both inefficient and unsafe. Recommended reading: How can I prevent SQL injection in PHP
From a database design standpoint, you should not be duplicating information from table members in table payment_log; storing a reference to the primary key of member is sufficient

How can I insert another row into another table, in PHP?

I can insert the list of questions but the problem is the answer? How
$myQuery= mysql_query("SELECT * FROM tblquestion, tblanswer WHERE questionID='$ctrlnum'");
$numRows = mysql_num_rows($myQuery);
then this will be the insertion of record:
$myQuery = mysql_query("INSERT INTO tblquestion VALUES ( '$ctrlnum','$question1','$question2','$question3','$question4','$question5',
'$question6','$question7','$question8','$question9','$question10') ");
$myQuery= mysql_query("INSERT INTO tblprelimanswer VALUES ('$ctrlnum','$answer1','$answer2','$answer3','$answer4','$answer5', '$answer6','$answer7','$answer8','$answer9','$answer10')
");
How can I insert the answers?
Change the code to
$myQuery = mysql_query("INSERT INTO tblquestion VALUES ($ctrlnum','$question1','$question2','$question3','$question4','$question5','$question6','$question7','$question8','$question9','$question10') ") or die (mysql_error());
$myQuery= mysql_query("INSERT INTO tblprelimanswer VALUES ('$ctrlnum','$answer1','$answer2','$answer3','$answer4','$answer5', '$answer6','$answer7','$answer8','$answer9','$answer10')") or die (mysql_error());
and post back what your error messages are
(This should be a comment but its rather long and easier to read with formatting)
While using a statement of the form
INSERT INTO tblquestion VALUES (...)
will work in MySQL, it is very bad practice not to explicitly state what columns each value maps to. e.g.
INSERT INTO tblquestion ( someId, avalue, adifferentthing ) VALUES (...)
In the relational database model, there is no concept of oredering of attributes within a record. Even on MySQL where such an approach is possible, semantic value is lost by omitting the atribute list and there is a risk of bugs being introduced if the schema is modified.
Further:
'$question1','$question2','$question3','$question4','$question5'....
implies that your data is not normalized. Each question should be in a seperate row.

Why do I get a 500 error? (MySQL php)

<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks

How to return variables that have been set in MySQL back to PHP

I have a PHP function which inserts multiple records into MySQL:
function commit_purchase($asset_type_ID, $org_ID, $asset_desc, $asset_cost, $date, $org_to_member_ID, $asset_ID, $purchaser_cur_invest, $purchaser_cred_deb, $purchaser_balance) {
global $db;
$query = "START TRANSACTION;
INSERT INTO assets
(asset_type_ID, org_ID, asset_desc, asset_cost, asset_value, purchase_date, is_approved)
VALUES
(:asset_type_ID, :org_ID, :asset_desc, :asset_cost, :asset_cost, :date, 1);
SET #asset_ID = LAST_INSERT_ID();
INSERT INTO cash_out
(org_to_member_ID, amount, description, date, is_approved, asset_ID)
VALUES
(:org_to_member_ID, :asset_cost, :asset_desc, :date, 1, #asset_ID);
SET #cash_out_ID = LAST_INSERT_ID();
INSERT INTO shares
(asset_ID, member_ID, percent_owner, is_approved)
SELECT assets.asset_ID, pending_asset_shares.member_ID, pending_asset_shares.percent_owner, pending_asset_shares.is_approved
FROM assets, pending_asset_shares
WHERE assets.asset_ID = #asset_ID;
DELETE FROM pending_asset_shares
WHERE asset_ID = :asset_ID;
DELETE FROM pending_assets
WHERE pending_asset_ID = :asset_ID;
INSERT INTO trans_log
(translog_id, trans_type, org_to_member_ID, date, purchaser, asset_ID, cur_invest, cash_out_ID, cred_deb, balance)
VALUES
(DEFAULT, 3, :org_to_member_ID, :date, :org_to_member_ID, #asset_ID, :purchaser_cur_invest, #cash_out_ID, :purchaser_cred_deb, :purchaser_balance);
COMMIT;";
$statement = $db->prepare($query);
$statement->bindValue(':asset_type_ID', $asset_type_ID);
$statement->bindValue(':org_ID', $org_ID);
$statement->bindValue(':asset_desc', $asset_desc);
$statement->bindValue(':asset_cost', $asset_cost);
$statement->bindValue(':date', $date);
$statement->bindValue(':org_to_member_ID', $org_to_member_ID);
$statement->bindValue(':purchaser_cur_invest', $purchaser_cur_invest);
$statement->bindValue(':purchaser_cred_deb', $purchaser_cred_deb);
$statement->bindValue(':purchaser_balance', $purchaser_balance);
$statement->bindValue(':asset_ID', $asset_ID);
$statement->execute();
$statement->closeCursor();
return $asset_ID;
I am trying to use the first INSERT statment's LAST_INSERT_ID (#asset) as a variable for my next function. The way I am calling the above function, in hopes of setting the variable, is:
$asset_ID = commit_purchase($asset_type_ID, $org_ID,.......etc.)
I am pretty sure my problem is somewhere around the "return $asset_ID" in my SQL statement. I have been able to do this successfully when using only 1 LAST_INSERT_ID call.
Nothing is being returned at all.
Ok, as mentioned in my comments, you can use beginTransaction to break this up. http://php.net/manual/en/pdo.begintransaction.php
Once you have done that, it's just a matter of getting the last inserted ID. You can use lastInsertId for that: http://php.net/manual/en/pdo.lastinsertid.php
Breaking this down into multiple queries would really be the best solution, but to answer your original question: If you want to get the value of MySQL variables in PHP, just execute a SELECT query:
$asset_ID = mysql_result( mysql_query( 'SELECT #asset_ID' ) );

How do I get all the ids of the row created by one multiple row insert statement

I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?

Categories