Ok so I execute the following code for inserting data into database:
$db_conn->beginTransaction();
$query = $db_conn->prepare('INSERT INTO mytable(name, user) VALUES(:name, :user)');
foreach($UploadData AS $DataValue)
{
$query->execute(array(':name' => $DataValue['Name'],':user' =>$_SESSION['user']));
}
$db_conn->commit();
Now in this code block execute() runs 100s time if I have that much data. Like before I use to do with basic mysqli concatenation and executes the query only once.
Will that can be done here with PDO also?
$SQL = 'INSERT INTO mytable (name, user) VALUES';
foreach( $UploadData AS $DataValue)
$SQL .= sprintf(" ( '%s', '%s' ),", $DataValue['Name'], $DataValue['user'] );
$SQL = substr($SQL, -1);
$query = $db_conn->prepare($SQL);
$query->execute();
Result
INSERT INTO mytable (name, user) VALUES ('VAL', 'VAL'), ('VAL', 'VAL') ....
Related
I have a numeric PHP variable named $quantity and based on the number set in this variable, I want to insert the same record in the MySQL table.
Example:
$quantity = '4';
$sql1 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql2 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql3 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql4 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
You can achieve this by using a loop and a prepared statement. You need to execute the same statement multiple times. This is also very useful if the values are dynamic and they could change, e.g. the values are coming from user input.
Prerequisite:
You need to open a connection to your database. If you use MySQL then the connection would look something like this:
$pdo = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8mb4", 'username', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
Now you can prepare a statement which we will execute in a loop multiple times.
$stmt = $pdo->prepare("INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());");
You can use any loop you like but for a simple scenario where we want the same code to be executed a number of times, a while loop is sufficient.
$quantity = 4;
while ($quantity--) {
$stmt->execute();
}
If it is easier for you, you can use for loop, too.
for($quantity = 0; $quantity < 4; $quantity++) {
$stmt->execute();
}
Try something like this:
// NOTICE - Make sure you are escaping any end-user supplied values correctly - See PHP docs for examples of how
$sql_template = 'INSERT INTO `table_quantity` (`username`, `code`, `quantity`, `data`) VALUES (\'John\', \'34438\', \'1\', now());';
$quantity = 5;
$sql = '';
foreach (range(1, $quantity) as $i) {
$sql .= $sql_template;
}
echo $sql;
See the following docs for explanations:
foreach
range()
append to string
Escape SQL values with PDO
Escape SQL values with MySQLi
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
I am entering objects from an array into a database.
I have an array called $graphObject
I am looping through the array like this,
foreach($graphObject['tagged_places']->data as $data) {
}
Then I want to take each one of these values and enter them in to the mysql DB with PDO
$data->id
$data->created_time
$data->place->id
$data->place->location->latitude
$data->place->location->longitude
$data->place->name
I am confused on how to write this loop to enter each one of these fields foreach time a new field exist.
Assuming the DB connection is open and the fields in the DB are named
id created_time place_id latitude longitude name
How would I write this with PDO?
What you probably want to do is to build your insert in a loop and then simply execute a single insert statement. So something like this:
$sql = <<<EOT
INSERT INTO table (
`id`,
`created_time`,
`place_id`,
`latitude`,
`longitude`,
`name`)
VALUES
EOT;
foreach($graphObject['tagged_places']->data as $data) {
// add values into string you can remove single quotes if not needed
// (i.e. for numeric data types)
$values = <<<EOT
(
'{$data->id}',
'{$data->created_time}',
'{$data->place->id}',
'{$data->place->location->latitude}',
'{$data->place->location->longitude}',
'{$data->place->name}'
),
EOT;
$sql .= $values;
}
$sql = rtrim(',', $sql);
// execute query using $sql
// assume you have properly instantiated PDO object in $pdo
$result = $pdo->query($sql);
if (false === $result) {
// something went wrong, so log an error
// this assumes you have not configured PDO to throw exceptions
error_log(var_export($pdo->errorInfo(), true));
} else {
// continue doing whatever you want to do
}
Create a prepared statement:
$stmt = $db->prepare('
INSERT INTO table
(id, created_time, place_id, latitude, longitude, name)
VALUES
(?, ?, ?, ?, ?, ?)
');
Execute it on each loop
foreach($graphObject['tagged_places']->data as $data) {
$stmt->execute(array(
$data->id,
$data->created_time,
$data->place->id,
$data->place->location->latitude,
$data->place->location->longitude,
$data->place->name
));
}
I want to execute a mysql query from php.
$sql = insert into q_links values ( 'garment.png', 'imgs\ques\p1\garment.png' );
I couldn't store the url as it is, rather it is being stored like this: imgsquesp1garment.png. But I want to store the url like: imgs\ques\p1\garment.png. So I tried this:
$sql = mysql_real_escape_string($sql);
But this way my $sql looks like:
insert into q_links values ( \'garment.png\', \'imgs\\ques\\p1\\garment.png\' );
which do not work in the mysql database.
I have to insert this url in the database for later use. The url is imgs\ques\p1\garment.png. How can I achieve this?
Update:
And I tried with the first comment which worked for me.
So the solution is:
$sql = "insert into q_links values ( 'garment.png', '".mysql_real_escape_string( 'imgs\ques\p1\garment.png' )."' );";
$url = "imgs\ques\p1\garment.png";
$url = mysql_real_escape_string($url);
$sql = "INSERT INTO q_links VALUES ('garment.png', '$url')";
As a side note, the mysql_* functions are deprecated, and you should move to Prepared statements with mysqli_* or PDO.
Example in PDO:
$pdo = new PDO("mysql:host=localhost;port=3306;dbname=mydb", "user", "password");
$stmt = $pdo->prepare("INSERT INTO q_links VALUES (?, ?)");
$stmt->execute(array("garment.png", "imgs\ques\p1\garment.png"));
$stmt->closeCursor();
Add the escape only for img field:
$sql = "insert into q_links values ( 'garment.png', '".mysql_real_escape_string( 'imgs\ques\p1\garment.png' )."' );"
don't escape the single quote, only the \
$var = "insert into q_links values ( 'garment.png', 'imgs\\ques\\p1\\garment.png');"
Why don't you store it with forward slashes as such?
$sql = insert into q_links values ( 'garment.png', 'imgs/ques/p1/garment.png' );
I can be like this:
$img=addslashes("imgs\ques\p1\garment.png");
$sql=insert into q_links values('garment.png',$img);
and while retriving you can use stripslashe();
You can use this code to enter image url in database
$url =mysql_real_escape_string('imgs\ques\p1\garment.png');
$sql = "insert into q_links values ( 'garment.png', '".$url."' );
if you execute the query:
insert into q_links values ( 'garment.png', 'imgs\ques\p1\garment.png' );
it will insert successfully in database
Use PDO. mysql_ is deprecated anyway.
$params = array('value_one','value_two')
$dbh = new PDO('credentials go here');
$sql = 'insert into q_links values ( ?, ? );';
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
Using PDO you would prepare your statement and then call execute it with the exacte variable you want. It would escape it all for you.
mysql_insert_id does not return the last inserted id when i place it inside a function.
im kinda confused why it does not.
here is my code:
function addAlbum($artist,$album,$year,$genre) {
$connection = mysql_connect(HOST,USER,PASS);
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastId.'","'.$lastId.'","'.$lastId.'","'.$lastId.'")';
$resultLink = mysql_query($sql);
if(!$resultArtist && $resultAlbums && $resultGenre && $resultYear && $resultLink){
echo mysql_error();
}
}
thanks in advance
adam
You are calling mysql_insert_id() once after four separate INSERTs, and using that ID four times for albumsId, artistId, genreId and yearId. That doesn't seem right.
You should also check that your tables are using AUTO_INCREMENT fields. If not, mysql_insert_id() will not return the insert ID. See the docs:
http://www.php.net/manual/en/function.mysql-insert-id.php
I highly recommend that you use prepared statements with mysqli::prepare, perhaps via PDO. It's ultimately simpler and safer. Here's an untested example:
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
$stmt_artist = $dbh->prepare(
'INSERT INTO `table_artist` (artistName) VALUES (?)'
);
$stmt_albums = $dbh->prepare(
'INSERT INTO `table_albums` (albumName) VALUES (?)'
);
$stmt_genre = $dbh->prepare(
'INSERT INTO `table_genre` (musicGenre) VALUES (?)'
);
$stmt_year = $dbh->prepare(
'INSERT INTO `table_year` (albumYear) VALUES (?)'
);
$stmt_link = $dbh->prepare(
'INSERT INTO `table_link` (albumsId, artistId, genreId, yearId) '.
'VALUES (?, ?, ?, ?)'
);
$stmt_albums->execute(array( $artist ));
$artist_id = $dbh->lastInsertId();
$stmt_albums->execute(array( $album ));
$album_id = $dbh->lastInsertId();
$stmt_genre->execute(array( $genre ));
$genre_id = $dbh->lastInsertId();
$stmt_year->execute(array( $year ));
$year_id = $dbh->lastInsertId();
$stmt_link->execute(array( $artist_id, $album_id, $genre_id, $year_id ));
You need to call it separately for each insert, and store the result of each call separately. Like this:
$sql = 'INSERT INTO `'.TABLE_ARTIST.'` (artistName) VALUES ("'.$artist.'")';
$resultArtist = mysql_query($sql);
$lastArtistId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$resultAlbums = mysql_query($sql);
$lastAlbumId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_GENRE.'` (musicGenre) VALUES ("'.$genre.'")';
$resultGenre = mysql_query($sql);
$lastGenreId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_YEAR.'` (albumYear) VALUES ("'.$year.'")';
$resultYear = mysql_query($sql);
$lastYearId = mysql_insert_id();
$sql = 'INSERT INTO `'.TABLE_LINK.'` (albumsId,artistId,genreId,yearId) VALUES ("'.$lastAlbumId.'","'.$lastArtistId.'","'.$lastGenreId.'","'.$lastYearId.'")';
Also, it only works if each of tables you're inserting into has AUTO_INCREMENT enabled.
Did you ever try to debug your code?
With echo() (for showing your SQL queries) or var_dump() (for checking the results of e. g. mysql_insert_id(), mysql_query()).
Also check mysql_error().
Furthermore be sure to set the resource identifier in your mysql_*() functions. It's possible to have more than just one open MySQL resource - so be sure to identify the resource.
For example:
$result = mysql_query($SQL, $connection);
$lastInsertID = mysql_insert_id($connection);
And - it's very important to know that mysql_insert_id() just works with tables which have an AUTO_INCREMENT-field.
And what's also interesting with your code: you call mysql_insert_id solely after the last of 5 queries. Is this really wanted? So you only receive the ID of your last INSERT query.