Before you spam as duplicate I have read through around 20-30 posts on this site about how to do this as well as others and I can't get mine to work so thats why i am asking the question.
I have the following code:
$lookupID = "SELECT ID FROM dungeon WHERE Name = '$loc'";
$result = mysqli_query($connection, $lookupID);
$row = mysqli_fetch_row($result);
$locID = $row['ID'];
$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', '$boss', '$type', '$loc', '$locID', '$diff')";
The purpose for the lookupID is to based upon the $loc value lookup in the other table what the locID value associated with it is and set $locID to that number. Currently when I run the query I get the following:
Error: INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', 'Godzilla', 'Lizard', 'Black Rock Hold', '', '4')
With the locID variable giving no value and so causing the error. Im sure its something simple and stupid I am doing but I am new to php and mysql so I hope you forgive me.
The mysqli_fetch_row function returns the array with enumerated keys, so you should use
$locID = $row[0];
If you want, you can use mysqli_fetch_assoc to get the row with associative keys instead.
Related
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
I am a beginner in php and mysql and am trying to write code to insert values into a table. The problem is some variables like $upval and $aday are inserted correctly but $course and $chour are inserted as zeros, notice that I echo the ($course and $chour) before the insert query and the echo prints the correct values(not zero).
$res1=mysql_fetch_object($result1);
$course =$res1->cid;
$result2= mysql_query("select thoure from $tbl_name3 where cid='$course'");
$res2=mysql_fetch_object($result2);
$chour =$res2->thoure;
$sql ="insert into $tbl_name2 (SID,Cid,Tid,Adate,Ahoure) values ('$upval','$course','2','$aday','$chour')";
$result = mysql_query($sql);
also I try another way to write query but the same problem
$sql ="insert into $tbl_name2 (SID,Cid,Tid,Adate,Ahoure) values ('$upval','".$res1->cid."','2','$aday','".$res2->thoure."')";
This is your SQL statement:
$sql=insert into absent (SID, Cid, Tid, Adate, Ahoure)
values ('65','','2','2014-05-06','')
If Cid is being inserted as 0, that is because Cid is a numeric type (probably integer of some sort) and strings are converted to numbers. So, '' is inserted as to 0 into a number. Why the value is set to an empty string, I do not know.
$sql = 'INSERT INTO photo '.
'(id,cid, path,date) '.
'VALUES (,`$cid`, `$new`,)';
There are four columns in the table, "photo".
1) id - auto increment
2) cid - $cid
3) path - $new
4) time - timestamp
Now I want to insert new data only to the cid and path fields. How can I do it with the above mentioned code
Try this:
//$con = you connection
$sql = "INSERT INTO photo (cid, path) VALUES ('$cid', '$new')";
mysqli_query($con, $sql);
this is as simple try this
$sql = "INSERT INTO photo (`cid`, `path`) VALUES ('$cid', '$new')";
Try this, if you know the value of id and date column value then pass it, other wise you just skip it or atlast pass the default value.
$sql = "INSERT INTO photo (cid, path,`date`) VALUES ('$cid', '$new',now())";
$sql = "INSERT INTO photo (cid, path,`date`) VALUES ('$cid', '$new',CURRENT_TIMESTAMP)";
1st of all... this is how you do debugging:
Run the query in phpmyadmin (echo query from php then run in phpmyadmin to see exactly what error you are getting, then adjust and test until it works properly
2nd: The ID. Either you lose it, like other people suggested above or you set it NULL and it gets auto incremented if it's set right in the schema.
I'm not trying to just give you a solution, i'm trying to get you some information, so you don't have to ask the next time.
$sql = "INSERT INTO photo (id,cid, path,date) VALUES (NULL,'".$cid."', '".$new."',now())";
mysqli_query($con, $sql);
You have some errors in your query
You have used tick mark around the variables which is invalid
Unwanted , at starting while entering values
This is not an error, but an advice:There is no need for breaking a query into several parts until it is large.
For inserting only cid and path Do like this
$sql = "INSERT INTO photo (cid, path) VALUES ('".$cid."', '".$new."')";
<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
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?