PHP insert multiple array into MySQL database - php

I have add/remove input box using jQuery for add video link and add into database like this:
<input name="video[]" class="" value="" />
<input name="video[]" class="" value="" />
I check and filter empty value than insert not empty value into my database like this:
$id = mysql_insert_id();
foreach(array_filter($_POST['video']) as $video_url) {
if (!empty($video_url)) {
$value['video_data'] = serialize((array(
array_filter($_POST['video'])
)));
SQL::insert("INSERT INTO " . NEWS_FILES . " (url, id,type) VALUES (?, ?, ?)", $value['video_data'], $id, "video");
}
}
Now, in database I see two row for id:
BUT, I need to insert one row for each id.
How do can I fix this ?
edit:
$id = mysql_insert_id();

Have you marked the id field in the database table as Auto Increment or not?
Because as per the current code, the $id is not updated anywhere. So it assumes the default value and inserts.
I would suggest to initialize $id before starting the foreach loop and then doing an increment after the SQL statement is executed
SQL::insert("INSERT INTO " . NEWS_FILES . " (url, id,type) VALUES (?, ?, ?)", $value['video_data'], $id, "video");
$i++;

You must create array values by php
$ar = new array();
$ar[]= null;
You submit form data multipart load
insert command by mysqldata
"Insert data into table db "
" for numbers all rows";

If you dont have auto increment of id, you can use
$id = "select max(id) from " .NEWS_FILES ; // execute sql and get maxid
than in your foreach add at a top $id++;

Related

Column NOT NULL but script is still creating a row

I have a script, which I use to INSERT data to my database. In HTML I have multiple textboxes. If data is entered into the textbox my script is running the INSERT statement. My script is also running the INSERT statement if there is no data entered into the textbox.
If there is no data entered into the textbox, the script creates an empty row in the database. I have tried to block this by changing the column to NOT NULL.
But it seems to be not working.
Does someone know the reason for that and how I can solve it?
Edit 1:
$sql1 = "SELECT * FROM product WHERE id='" . $id1 . "' AND user_id='" . $_SESSION['USER_ID'] . "'";
$result1 = $link->query($sql1);
if ($result1->num_rows > 0) {
$sql11 = "UPDATE product SET voorraad = quantity -" . $quantity . " WHERE user_id='" . $_SESSION['USER_ID'] . "' AND id='" . $id1 . "'";
if(mysqli_query($link, $sql11)){
echo '<p>product1 is updated</p><br />';
} else {
echo '<p>error</p>';
}
} else {
$query1 = "INSERT INTO product(user_id, name, price, tax) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query1);
$exec1 = $stmt->execute(array($_SESSION['USER_ID'], $name1, $price1, $tax1));
if($exec1){
echo '<p>product1 is created</p>';
} else {
echo '<p>error</p>';
}
}
You are inserting empty strings, and empty string are not NULL, to check for NULL error do:
INSERT INTO addresses (street, city, state, zip) VALUES (NULL, NULL, NULL, NULL);
and you will see error. The NOT NULL checks only for values that are not NULL.
To prevent empty string either you have to use triggers, or do the checks on server side programming language to convert empty strings to NULL before performing INSERT query. An example trigger for INSERT may be like: (this is just an example)
CREATE TRIGGER avoid_empty
BEFORE INSERT ON addresses
FOR EACH ROW
BEGIN
IF street = '' THEN SET street = NULL END IF;
END;
you can verify variables and execute query if variable is not null & empty ,else write values are null, must pass data

How to write multiple insert in multiple tables using the same form PHP

I have a problem with inserting data into two different tables: When a new member is created, it will be insert into member and grade tables after getting the id course from course table. I used INSERT for both of them at the same time with a multi query function but it doesn't work.
Can you help me please?
The form:
<form>
<input type="text" name='m_fName'>
<input type="text" name='m_lName'>
<input type="text" name ='m_nId'>
</form>
Php
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId)
VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');
INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
mysqli_multi_query($conn,$sql);
$id = $re['c_id'];
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$sql .="INSERT INTO grade(c_id,m_nId) VALUES( '$id','$_POST[m_nId]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Hope this will help. but try to first validate the posted data. check if isset .you did not show in the are you using post and the page you are posting your data
Answer above is the correct one, alternative way is the code below
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$act = mysqli_query($conn,$sql);
if($act) {
$sql2 = "INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
$act2 = mysqli_query($conn,$sql2);
}

Insert into database with unknown number of input type texts php

Okay so lets say i have an undefined number of selected rows in my database. I used while loop so the input area keeps increasing.
My question is how do i insert into my database without knowing how many values should be inserted? Should i use some kind of loop?
<form method = "POST" action = "save.php">
while($row = mysqli_fetch_assoc($result)){
<input type = "text" name="txtname">
}
<input type="submit" name="btnsubmit" value = "Save">
</form>
In most cases inserting multiple records with one Insert statement is much faster in MySQL than inserting records with for/foreach loop in PHP.
Let's assume $column1 and $column2 are arrays with same size posted by html form.
You can create your query like this:
<?php
$query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
$query_parts = array();
for($x=0; $x<count($column1); $x++){
$query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
}
echo $query .= implode(',', $query_parts);
?>
If data is posted for two records the query will become:
INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data',
'data')

How do i get the last ID's from the inserted data?

I have an option to send multiple rows into an table, i'm using an foreach to do that:
if (is_array($add['jobname'])) {
$insert = "INSERT INTO job_offers (job_category, status) VALUES ";
foreach ($add['job_name'] as $key => $value) {
$insertedval[] = "
('" . safe($add['job_category'][$key]) . "',
'" . safe($add['status'][$key]) . "')";
}
}
$insert .= implode($insertedval, ",");
$last_id = db_query($insert, '+id?'); //gets the last generated ID, its a function that i created, and working great.
The problem is that i want to get the last ID, and i'm getting, but i'm inserting multiple rows into the database, and i want to get the ID's from all the inserted values, because they are being sent at the same time.
I can't put the $last_id variable inside the foreach loop, what do i do?
ps: i'm using auto increment
Can you try something like this?
$db = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$db->beginTransaction();
$stmt = $db->prepare('INSERT INTO job_offers (job_category, status) VALUES (?, ?)');
$insertedIds = array();
foreach ($add['job_name'] as $key => $value) {
$stmt->execute($add['job_category'][$key], $add['status'][$key]));
$id = $db->lastInsertId();
array_push($insertedIds, $id);
}
$db->commit();
the ids should be in the insertedIds.
You can't.
Only by saving the the last index id before the inserted data, and than do it again after and select all the ids between that range.
SELECT ID FROM job_offers ID BETWEEN last-before-insert AND last-after-insert
You don't need a custom function to get the last insert id , there is already one built into both php mysqli and php PDO extensions .
As far I know , the last insert id is session aware , meaning you will get the last insert from the current insert requests only .
Get last inset id using PHP PDO
$pdo->lastInsertId();
Get last insert id using mysqli
$mysqli->insert_id;
$pdo and $mysqli are the connection variables

Running a mysql query multiple times using values from an array in the WHERE clause

I need to run a database query multiple times depending in the User ID. Heres my query:
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234')";
I have an array of user ID's from a seperate query shown here:
while($rows=mysql_fetch_array($allresult)){
$birthdays_today[] = $rows['user_id'];
}
echo $birthdays_today[0];
I want the query to run, but there the "userid" = XXXXX in the query, I want that to be populated with a user ID from the array. This means the query must be ran multiple times and each time, the next ID is entered into the query..
Does this make sense?
Thanks :)
MySQL has a bulk insert feature.
$query1="INSERT INTO wp_scloyalty (userid, value) VALUES ('XXXXX', '01234'), ('XXX2', '23234'), ('XXXX3', '3434545')"
<?php
$query = "INSERT INTO wp_scloyalty (userid, value) VALUES ";
$usersToInsert = array();
foreach($birthdays_today as $user_id){
$usersToInsert[] = "($user_id, '01234')";
}
$query .= implode(',', $usersToInsert);
?>
Use a for loop and change out the query with sprintf() and string formatting.
<?php
foreach($birthdays_today as $uid){
mysql_query(); // ...
}
?>
but
<?php
while($rows=mysql_fetch_array($allresult)){
mysql_query(); // use $rows['user_id'] here
}
?>
I will only display the script after your $birthdays_today[] has been populated.
foreach( $birthdays_today as $thisID )
{
mysql_query( "INSERT INTO wp_scloyalty (userid, value) VALUES ('{$thisID}', '01234');" );
}

Categories