I have made this code to put in a database some webradio data from an xml witch is working, the problem is if the mp3 file as no album it messes up the data entry, can someone point a way to if $pieces[1] exists run the code and add the album if not don't do anything, and add the others in the right place.
$title = $xml->SONGTITLE;
$pieces = explode("-", $title);
$pieces[0] = trim($pieces[0]);
$pieces[1] = trim($pieces[1]);
$pieces[2] = trim($pieces[2]);
// performing sql query
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)";
$result = mysqli_query($con, $sql);
Maybe just add : if ($pieces[1]!="") ?
$title = $xml->SONGTITLE;
$pieces = explode("-", $title);
$pieces[0] = trim($pieces[0]);
$pieces[1] = trim($pieces[1]);
$pieces[2] = trim($pieces[2]);
if ($pieces[1]!="")
{
// performing sql query
$sql = "INSERT INTO test_xml (`title`, `album`, `artist`) VALUES ('$pieces[2]', '$pieces[1]', '$pieces[0]') ON DUPLICATE KEY UPDATE time = now(), album = VALUES(album)";
$result = mysqli_query($con, $sql);
}
Yes that quite easy you just need to check if the value has been set.
if(isset($value_to_check))
{
//true - your item has a value.
}
else
{
//do somthing else.
}
Related
I made a form for pharma products where user select the manufacturers name and write the details of the project. Everything is up and running fine except only this issue. Its been hours and i cant figure it out.
The problem is Its only selects the first row and ignore new entries. What i want is it will select every row or every new entry and insert into second database here the code is working with no errors but update only the first row.
//Select Everything from database
$perm = "SELECT * FROM test";
$result34 = mysqli_query($dbc, $perm);
if ($perm) {
//How many rows
$count = mysqli_num_rows($result34);
//Retrieve data
if($count>=1) {
$rows = mysqli_fetch_array($result34);
$namex= $rows['name'];
$categoryx = $rows['category'];
//takeout the spaces and strip tags
$namey = strip_tags($namex);
$category = str_replace(' ', '', $category);
//INSERT INTO TABLES
$sql34 = "INSERT INTO final1 (Name, Category) VALUES ($namey, $category);";
$result55 = mysqli_query($dbc, $sql34);
}
}
With prepared statement:
$sql2 = "INSERT INTO final1 (Name, Category) VALUES (?, ?);";
$stmt1 = mysqli_stmt_init($dbc);
if (!mysqli_stmt_prepare($stmt1, $sql2)) {
echo "SQL error";
} else {
mysqli_stmt_bind_param($stmt1, "ss", $namey, $category);
mysqli_stmt_execute($stmt1);
}
you need while loop
//Select Everything from database
$perm = "SELECT * FROM test";
$result34 = mysqli_query($dbc, $perm);
if ($result34) {
//How many rows
$count = mysqli_num_rows($result34);
//Retrieve data
if($count>=1) {
while($rows = mysqli_fetch_array($result34) ){
$namex= $rows['name'];
$categoryx = $rows['category'];
//takeout the spaces and strip tags
$namey = strip_tags($namex);
$category = str_replace(' ', '', $category);
//INSERT INTO TABLES
$sql34 = "INSERT INTO final1 (Name, Category) VALUES ($namey, $category);";
$result55 = mysqli_query($dbc, $sql34);
}
}
}
?>
i need some help , i have simple code like count rows in php, i use PDO ,
so i check if rowCount > 0 i do job if no other job but i have it in foreach function, in first step i get true result but in other i get invalid
so i think it is function like a closeCursor() in PDO but i try and no matter . maybe i do it wrong ?
it is part of my code
public function saveClinicCalendar($post){
$daysItm = '';
$Uid = $post['Uid'];
$ClinicId = $post['ClinicId'];
$type = $post['type'];
$resChck = '';
foreach($post['objArray'] as $arr){
foreach($arr['days'] as $days){
$daysItm = $days.",".$daysItm;
}
$daysItm = substr($daysItm, 0, -1);
$dateTime = $arr['dateTime'];
$sqlChck = 'SELECT * FROM clinic_weeks WHERE dates = :dates AND Uid = :Uid AND category = :category AND Cid = :Cid AND type = :type';
$resChck = $this->db->prepare($sqlChck);
$resChck->bindValue(":dates",$dateTime);
$resChck->bindValue(":Cid",$ClinicId);
$resChck->bindValue(":type",$type);
$resChck->bindValue(":Uid",$Uid);
$resChck->bindValue(":category",$Uid);
$resChck->execute();
$co = $resChck->rowCount();
if($co > 0){
/*UPDATE*/
$sql = 'UPDATE clinic_weeks SET dates = :dates ,time = :time, Cid = :Cid, type = :type, Uid = :Uid, category = :category ';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}else{
/*INSERT*/
$sql = 'INSERT INTO clinic_weeks (dates,time, Cid,type,Uid,category) VALUES (:dates,:time, :Cid,:type,:Uid,:category)';
$res = $this->db->prepare($sql);
$res->bindValue(":dates",$dateTime);
$res->bindValue(":time",$daysItm);
$res->bindValue(":Cid",$ClinicId);
$res->bindValue(":type",$type);
$res->bindValue(":Uid",$Uid);
$res->bindValue(":category",$Uid);
}
$res->execute();
$resChck->closeCursor();
$resChck = null;
$daysItm = '';
}
}
what i am doing wrong?
many thanks to Barmar, he suggest me a true answer.
here is a code
$sql = "INSERT INTO clinic_weeks
(`timestam`,`time`,dates,Cid,type,Uid,category)
VALUES
('$timestamp','$daysItm','$dateTime','$ClinicId','$type','$Uid','$Uid')
ON DUPLICATE KEY UPDATE `time` = '$daysItm' ";
I use there "ON DUPLICATE KEY UPDATE" and it`s work perfectly!
instead a big code top of page i make a two line of code.
I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else
I’m wondering if this is possible, I’ve search and haven’t found anything so about to give up.
I’m looking to do the following for example, note i do not want to use a foreach as that converts it into single queries.
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$sql = "update ppl set firstname = $b, lastname = $c where id = $a";
The same can be said for an insert.
$sql = "insert into ppl (firstname,lastname) value ($b,$c)";
The main reason I'm looking to do this is to optimise the db a bit. There are a lot of single queries that (if this method is possible) could be converted into 1 single query.
Thanks in advance.
if (count($a) <= 0)
return; // nothing to do
$sql = "INSERT INTO table (id, firstname, lastname) VALUES";
while (count($a) > 0)
{
$id = array_shift($a);
$fname = array_shift($b);
$lname = array_shift($c);
$sql .= sprintf("('%s', '%s', '%s'),", mysql_real_escape_string($id), mysql_real_escape_string($fname), mysql_real_escape_string($lname));
}
$sql = substr($sql, 0, -1); //remove last comma
$sql .= " ON DUPLICATE KEY UPDATE firstname=VALUES(fname), lastname=VALUES(lname)";
//run your sql
this will allow you to run all of them at once.
For update you can do as follows
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$i=0;
foreach($b as $fname){
if( !empty($b[$i]))
{
$sql = "update ppl set firstname = '".$b[$i]."', lastname = '".$c[$i]."' where id = $a[$i]";
}
$i++;
}
and for insert you can try
$i=0;
$var = '';
foreach($b as $fname){
if( !empty($b[$i]))
{
$var .= "(".$a[$i].",'".$c[$i]."','".$b[$i]."') ";
}
$i++;
}
if(!empty($var)){
$sql = "insert into ppl(id,firstname,lastname) values ".$var;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
create a mysql record if it doesnt exist, else update it
I have created a bit of PHP that gets data from a CSV and updates a Database Table to match the CSV's data.
My next task is, To check if the record exists, based on the unique column (sku). If it does exist update the database table dependant on the change.
Otherwise if that SKU column doesnt match do the INSERT.
The code I've got at the moment runs, However the issue I have is that if a new item is created it seems to run the update through the already existing records.
My code can be found on Pastebin
Or also here...
<?php
$con = mysql_connect("localhost", "root", "");
if(!$con)
{
die('Could not connect' . mysql_error());
}
mysql_select_db("db_lemonstand", $con);
class csvIterator extends LimitIterator
{
public function __construct($path)
{
$csv = new SplFileObject($path);
$csv->setFlags(SplFileObject::READ_CSV);
parent::__construct($csv, 1);
}
}
foreach (new csvIterator('data/catalogue.csv') as $entry) {
$name = $entry[23];
/* Replace Strings To Make URL Name */
$search_array = array(" ", "/", "+");
$replace_array = array("-");
$url_name = strtolower($name);
$url_name = str_replace($search_array, $replace_array, $url_name);
$long_desc = $entry[9];
$short_desc = $entry[23];
$manufacturer = $entry[11];
$price = $entry[15];
$sku = $entry[2];
$weight = $entry[29];
$width = $entry[30];
$height = $entry[5];
$enabled = '1';
$created_at = date('Y-m-d H:i:s');
$product_type_id = '1';
$tax_class_id = '1';
echo '<pre>';
print_r($entry);
echo '</pre>';
// Check see if products' SLU already exists or not
$product_exists = "SELECT sku FROM shop_products WHERE sku = '$sku'";
$result = mysql_query($product_exists, $con);
$exists = mysql_num_rows($result);
if($exists == 0 )
{
$insert = "INSERT INTO shop_products (name, description, short_description, url_name, price, sku, weight, width, height, enabled, created_at, tax_class_id, product_type_id) VALUES ('$name', '$long_desc', '$short_desc', '$url_name', '$price', '$sku', '$weight', '$width', '$height', '$enabled', '$created_at', '$tax_class_id', '$product_type_id')";
$insert_data = mysql_query($insert, $con);
}
else
{
$update = "UPDATE shop_products SET name = '$name', description = '$long_desc', short_description = '$short_desc', url_name = '$url_name', price = '$price', sku = '$sku', weight = '$weight', height = '$height', enabled = '$enabled', created_at = '$created_at', tax_class_id = '$tax_class_id', product_type_id = '$product_type_id'";
$update_data = mysql_query($update, $con);
if (!mysql_query($update,$con))
{
die('Error: ' . mysql_error());
}
}
}
You can use
INSERT INTO mytable on DUPLICATE KEY UPDATE...
You must set unique key for your table (one or more fields) and than you can use this ability.
In my example I have unique key (template, date)
$sql = 'INSERT INTO myTable
(`template`,`date`,`count`) VALUES
("' . $template . '","' . $curDate . '", 1)
ON DUPLICATE KEY UPDATE count = count + 1';
Store store you fields in a var as $fields or anything else that you want and execute this query for that you need a single field as reference that's why i included $Id
INSERT INTO table_name SET id = '$Id', $fields ON DUPLICATE KEY UPDATE $fields