How do I modify this MySQL INSERT Query for multiple rows? - php

I am attempting to insert records for Artists, Songs and Record Labels, whilst checking that the data does not already exist in the Database.
The following code is from Mike Fenwick.
<?php
$query = "SELECT id FROM table WHERE unique1=value1 AND unique2=value2…";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET unique1=value1 AND unique2=value2…";
$insert_result = mysql_query($query);
$id = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$id = $row['id'];
}
return $id;
?>
I need to modify this to check if three unique values exist already (from 3 separate tables), and if not, insert them. Here is my attempt:
<?php
$query = "SELECT id FROM artistsTable WHERE artistName='Beyonce'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET artistName='Beyonce' AND artistImage='beyonce.jpg'";
$insert_result = mysql_query($query);
$artistID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$artistID = $row['artistID'];
}
return $artistID;
$query = "SELECT id FROM recordLabelTable WHERE labelName='Columbia Records'";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO table SET labelName='Columbia Records'";
$insert_result = mysql_query($query);
$labelID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$labelID = $row['labelID'];
}
return $labelID;
$query = "SELECT id FROM songTable WHERE trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$select_result = mysql_query($query);
if (!mysql_num_rows($select_result)) {
$query = "INSERT INTO songTable SET trackTitle='Crazy in Love' AND artistID=".$artistID." AND labelID=".$labelID."";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
}
else {
$row = mysql_fetch_assoc($select_result);
$songID = $row['songID'];
}
return $songID;
?>
I'm assuming that there must be a more efficient way to do this. Any ideas would be much appreciated.

Using basic inset / ignore syntax you could do something like this.
A couple of inserts to put in the artist details and label details, then an INSERT based on a SELECT:-
<?php
$query = "INSERT IGNORE INTO artistTable (artistName, artistImag) VALUES('Beyonce', 'beyonce.jpg')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO labelTable (labelName) VALUES('Columbia Records')";
$insert_result = mysql_query($query);
$query = "INSERT IGNORE INTO songTable (trackTitle, artistID, labelID)
SELECT 'Crazy in Love', a.artistID, b.labelID
FROM artistTable a
INNER JOIN labelTable b
ON a.artistName = 'Beyonce'
AND a.artistImag = 'beyonce.jpg'
AND b.labelName = 'Columbia Records'";
$insert_result = mysql_query($query);
$songID = mysql_insert_id();
return $songID;
?>
As #LoganWayne says, you probably should use MySQLi .

<?php
/* ESTABLISH CONNECTION */
$con=mysqli_connect("Host","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
/* FOR artistsTable TABLE */
$query = "SELECT id FROM artistsTable WHERE artistName='Beyonce'";
$select_result = mysqli_query($con,$query); /* EXECUTE QUERY */
if (mysqli_num_rows($select_result)==0) { /* IF QUERY'S RESULT IS 0 */
$query = "INSERT INTO table SET artistName='Beyonce' AND artistImage='beyonce.jpg'";
$insert_result = mysqli_query($con,$query); /* EXECUTE INSERT QUERY */
} /* END OF IF */
else {
while($row = mysqli_fetch_array($select_result)){
$artistID = mysqli_real_escape_string($con,$row['artistID']); /* ESCAPE STRING */
} /* END OF WHILE LOOP */
} /* END OF ELSE */
/* FOR recordLabelTable TABLE */
$query = "SELECT id FROM recordLabelTable WHERE labelName='Columbia Records'";
$select_result = mysqli_query($con,$query); /* EXECUTE SELECT QUERY */
if (mysqli_num_rows($select_result)==0) { /* IF QUERY'S RESULT IS 0 */
$query = "INSERT INTO table SET labelName='Columbia Records'";
$insert_result = mysqli_query($con,$query); /* EXECUTE INSERT QUERY */
}
else {
while($row = mysqli_fetch_array($select_result)){
$labelID = mysqli_real_escape_string($con,$row['labelID']); /* ESCAPE STRING */
}
}
/* FOR songtable TABLE */
$query = "SELECT id FROM songTable WHERE trackTitle='Crazy in Love' AND artistID='$artistID' AND labelID='$labelID'";
$select_result = mysqli_query($con,$query); /* EXECUTE SELECT QUERY */
if (mysqli_num_rows($select_result)==0) {
$query = "INSERT INTO songTable SET trackTitle='Crazy in Love' AND artistID='$artistID' AND labelID='$labelID'";
$insert_result = mysqli_query($con,$query); /* EXECUTE QUERY */
} /* END OF IF */
else {
while($row = mysqli_fetch_array($select_result)){
$songID = mysqli_real_escape_string($con,$row['songID']);
} /* END OF WHILE LOOP */
}
?>
SUMMARY:
Used at least MySQLi instead of deprecated MySQL.
Replaced fetch_assoc() function with fetch_array() function.
Used mysqli_real_escape_string() function to prevent some of SQL injections.
Cleaned your code. You have misplaced apostrophes(') and double quotes(") hanging around.

Related

Inserting data into sql it inserts two into rows, and i dont know why

When Inserting data into SQL it inserts two into rows, and I don't know why.
most probably of the if statement I added after the results you can find it as my comment:
// id_no update
And I used the select query two times to fetch the id and make it an auto-increment thing.
my table:
<?PHP
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
?>
<?PHP
if(isset($_POST['add_id']))
{
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if(mysqli_query($con,$sql))
{
$query = "SELECT id_no FROM db_name ORDER BY id_no DESC";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
$lastid = $row['id_no'];
if(empty($lastid))
{
$number = "SX000001";
}
else
{
$idd = str_replace("SX", "", $lastid);
$id = str_pad($idd + 1, 6, 0, STR_PAD_LEFT);
$number = 'SX'.$id;
}
}
else
{
echo "Record Faileddd";
}
if($result)
{
$success="Post has been added successfully";
} else
{
$error="Something went wrong!";
}
$id_no = '';
}
?>
You should check if $result is truthy to see if the insertion succeded (without running another query):
$id_no = mysqli_real_escape_string($con,$_POST['id_no']);
$sql="INSERT INTO `db_name`(`id_no`) VALUES ('$id_no')";
$result=mysqli_query($con,$sql);
// id_no update
if($result)
{
...
}

select all records and the rest

here is a simple mysqli query to select specific records from my mysql database:
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
}
The question is:
How can I get (best practices) all the other records, which will not be selected with this query filter?
It can be like
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
$query2 = "select * from 'myTable' WHERE 'bookid' != ".$zeile['ID']."'";
$result2 = $db -> query($query2);
// do something...
}
}
OR
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
$query2 = "select * from 'myTable' WHERE 'bookid' != '".$data['ID']."'";
$result2 = $db -> query($query2);
while($zeile2 = $result2-> fetch_object()){
// do something...
}
}
Running successive, more or less identical, queries in a loop is fundamentally a bad way to do things. Create a list of $data['ID'] values you want to work with, then use one query to retrieve all the rows IN that list, and a second query to retrieve everything NOT IN that list:
Important: This code assumes that the values in $getData[]['ID'] can be trusted. i.e. they have been validated before entry to this code, or they come from a trusted source.
// Create a list:
$inList = '('.implode(',', array_column($getData, 'ID')).')';
$sqlIn = "SELECT * FROM `myTable` WHERE `bookid` IN $inList";
// run the query. Check for errors
if (($result = $db->query( $sqlIn )) === false) {
throw new Exception($db->error);
}
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
// Now use the same list to exclude those rows
$sqlOut = "SELECT * FROM `myTable` WHERE `bookid` NOT IN $inList";
// run the query. Check for errors
if (($result = $db->query( $sqlOut )) === false) {
throw new Exception($db->error);
}
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}

PHP: find out the primary key of the just-inserted row data

I'm trying to find out the id value which is the primary key of the table. In order to do so, I implemented a code like this.
public function addNewPost($userName, $content) {
// insert post information into the data.
$query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
$result = mysqli_query($this->db->connect(), $query);
$id = mysqli_insert_id($this->db->connect());
if ($result) {
// get the row data with the found primary key
$query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
$result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);
return mysql_fetch_array($result_row_data);
} else {
return false;
}
}
Here I tried to get the id by running thhe $id = mysqli_insert_id($this->db->connect()); command, but it doesn't seem to work.
Any solutions?
You need to use a connection variable not a function call. A second call to connect() is returning a new connection.
$connection = $this->db->connect();
$result = mysqli_query($connection, $query);
$id = mysqli_insert_id($connection);
Or if you keep a variable in the db class which makes sense:
$result = mysqli_query($this->db->connection, $query);
$id = mysqli_insert_id($this->db->connection);
Save the connection
public function addNewPost($userName, $content) {
// insert post information into the data.
$query = "INSERT INTO posts(uploader, content, uploaded_at) VALUES('$userName', '$content', NOW())";
$con = $this->db->connect();
$result = mysqli_query($con, $query);
$id = mysqli_insert_id($con);
if ($result) {
// get the row data with the found primary key
$query_get_row_data = "SELECT * FROM posts WHERE id = '$id'";
$result_row_data = mysqli_query($this->db->connect(), $query_get_row_data);
return mysql_fetch_array($result_row_data);
} else {
return false;
}
}

how to return value of selected id in database php

I insert in the database a csv file. how will i return the id and use it to insert in another table. it always displays array to string conversion errror. is there something wrong with "return"
here is my controller
public function uploadThree(){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$appname = $fileop[0];
$servname = $fileop[1];
$ciname = $fileop[2];
$servid = $this->some_model->insertBulkServ($servname); //i tried to get the value here then insert below
$appid = $this->some_model->insertBulkSingleApp($appname);//i tried to get the value here then insert below
$this->some_model->insertBulkCI($ciname);
$this->some_model->ASMAP($appid,$servid);
}
if($success == TRUE)
redirect(base_url().'some_controller/uploadPage');
}
MODEL
public function insertBulkServ($service) {
/* Inserts csv file for a service */
$service = $this->db->escape_str($service);
$queryStr = "Select service from appwarehouse.service where service = '$service' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
//in here how do i get the ID how do i return it
}else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function insertBulkSingleApp($app_name) {
/* Inserts csv file for an application */
$app_name = $this->db->escape_str($app_name);
$queryStr = "Select * from appwarehouse.application_table where app_name = '$app_name' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
else{
$queryStr = "INSERT INTO appwarehouse.application_table(app_name)
VALUES ('$app_name');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function ASMAP($appid,$servid) {
$appid = $this->db->escape_str($appid);
$servid = $this->db->escape_str($servid);
$queryStr = "Select * from appwarehouse.app_service where app_id = '$appid' AND serv_id = '$servid' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
return true;
}
else{
$queryStr = "INSERT INTO appwarehouse.app_service(app_id,serv_id)
VALUES ('$appid','$servid');";
$query = $this->db->query($queryStr);
return true;
}
}
What you probably want is:
$this->db->insert_id()
The insert ID number when performing database inserts.
More Info: http://ellislab.com/codeigniter/user-guide/database/helpers.html
You need to do it it is very simple
After the query insert
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
Instead of select use this
return $this->db->insert_id();
Or if you really need to return the object
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
Return id instead of object
return $query->row()->id;
One more thing to note. insert_id is the last inserted id so you dont have to run select query to get id.
Also use row() to select single record. result() selects multiple records so you will get an array. see here.

Half of PHP script not submitting

I have made a php script to pull from two different tables within the same database. After the data is pulled, it is put into another table that will hold that specific information for later use. Right now, it will submit the userid and username but will not submit the puid variable I have stated.
Here is the script
include('data.php');
//Database Connection
$con=#mysql_connect("$ip", "$guser", "$gpass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($forums, $con)
or die(mysql_error());
$search = $_POST['term'];
$sql = mysql_query("select userid, usergroupid, username from $users where username like '%$search%'");
while ($row = mysql_fetch_array($sql)) {
$id = $row['userid'];
$name = $row['username'];
$ugid = $row['usergroupid'];
}
if ($ugid == '21') {
$sql4 = "INSERT INTO $vip (fuid, username) VALUES ('$id', '$name')";
$res2 = #mysql_query($sql4, $con) or die(mysql_error());
$sql2 = mysql_query("SELECT $id, field5 FROM $userfield");
while ($row = mysql_fetch_array($sql2)) {
$puid = $row['field5'];
}
$sql3 = "INSERT INTO $vip (puid) VALUES ('$puid')";
$res = #mysql_query($sql3, $con) or die(mysql_error());
echo 'Completed';
} else {
echo 'User is not VIP';
}
you are not doing those queries for all retrieved rows.you should get those queries inside foreach loop otherwise only the last row will be effected!

Categories