php mysql insert (when something is repeart, insert an empty value) - php

I want insert some articles. I want make a judge first, if the image value has already in the database, insert a null value.
For more explain:
If there have these data:
title1,image1
title2,image2 //this is image2 first appear, so insert it
title3,image2 //image2 has already in the database, so insert an empty value for just image field
title4
title5,image3
the final data insert into the database should like this:
title | image
title1,image1
title2,image2
title3
title4
title5,image3
Here is my code, but it still insert the repeat value into the database. So is there any one can help me? thanks.
foreach{//first here has a foreach to make all the articles as a queue
...
if(!empty($image)){ //first judge if the insert article had a image value
$query1 = mysql_query("select * from articles where .image = '".$image."' ");
while ($row = mysql_fetch_array($query1)) {
$image1 = $row['image'];
}
}
if(!empty($image1)){ //make a query first if the image has already in the database
mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','' ");
}else{
mysql_query("INSERT INTO articles (title,image) SELECT '".$title."','".$image."' ");;
}
}

Your first query contains an error. You have to remove the dot before "image":
where **.**image

As Francesco mentioned that dot could be a problem for that query.
Not really clear what you are trying to do here. But if you are trying to stop same image file being stored twice then you should use something like this below:
function is_same_file( $image1, $image2 ){
if( filesize($image1) != filesize($image2)
return false;
if( hash_file('md5', $image1) != hash_file('md5', $image2) )
return false;
return true;
}

Related

PHP Query to UPDATE/DELETE a dynamically generated input field in a table

I have a Table where user can create row with adding input fields dynamically (combination with jquery). I'm successfully able to insert it into the mysql database.
If users want to edit the added already existing fields, I have an edit page where the values are fetched from the mysql DB and populated again into the dynamically creatable table.
Now there are the below probabilities:-
User only makes minor changes on the existing values. In that case
the table has to be UPDATED with the changed values
User Deletes one/multiple row(randomly selected and as per users wish). So when form submitted the php query should only DELETE that perticular row/s in the DB.
User ADDS another row to the previous existing row values, in that case the php query should UPDATE the previous values and INSERT the newly added row values.
The above sequence is not necessarilly restricted the same order. User can perform all the above three function simultaneously at the same time.
Now my problem is(only for the backend) I'm finding a hard time to frame a php & sql query so as to update to the mysql.
my php
if(isset($_POST['submit'])){
$number1 = count($_POST['item']); //
for($i=0; $i<$number1; $i++){
$item = strip_tags(trim($_POST['item'][$i]));
$description = strip_tags(trim($_POST['description'][$i]));
$unitcost = strip_tags(trim($_POST['unitcost'][$i]));
$qty = strip_tags(trim($_POST['qty'][$i])); // Quantity
$sno = strip_tags(trim($_POST['sno'][$i]));// serial number
//QUERY1 if minor updates to above variable then UPDATE (eg, qty value is changed from 3 to 4)
//QUERY2 if row is deleted then DELETE that particular row from db (eg, sno 3 deleted from the table should DELETE corresponding mysql DB values also)
//QUERY3 if row is added then that particular row values should be INSERT (eg, sno 4 is added which is not in the mysql db. So this has to be INSERTED.)
}
}
Pardon me to have asked such question. I'm wasting a whole lot of time with the above queries unable to execute properly. I only require an idea not necessarily the whole code.
Hope all of you out there would advice me some ideas on how this could be implemented. Thanks for the help in advance. Expecting a positive reply.
NB: Just to remind you again, The front end is a Dynamically ADD/DELETE Input Field table
This sounds like a frontend problem. You need to define how you tell the backend whats happening.
<input name="items[$i][name]" />
This will show up as nice array to loop through in php.
foreach($_POST[items] AS $item){
if( $item['delete'] ){
//delete code
}
}else{
//Insert/Update
}
If you want to delete something simply make the field hidden and add a flag to it.
<input type="hidden" name="items[$i][delete]" value="1" />
<input type="hidden" name="items[$i][id]" />
Thank for the reply, appreciate #ckrudelux and #codefather for their intention to help me.
Although their advise didn't help me to structure my query. So I had a long workaround and found out below solution. I'm posting the solution because I couldn't find any article online when it comes to UPDATE/DELETE a dynamically generated input table.
Hope this would be of help to someone.
So what I did basically is that I took all the values into array.
In my dynamically generated add input table code, I added an <input type="hidden" name="sno[]" value="newrow">. So this will be clubbed with the form post. I'm using the normal html post and not ajax.
now my submit.php has ben changed to below
if(isset($_POST['submit'])){
$productid = $_POST['productd'];// No striptag functions
// due to illustration purpose
// First of all, we need to fetch the querying db table.
// This is required in order to compare the existing row values
// with the posted values
$fetchproduct = $link->prepare("SELECT * FROM product WHERE productid=?");
$fetchproduct ->bind_param('s',$productid);
$fetchproduct ->execute();
$fetchresult = $fetchproduct ->get_result();
$serialnumber=array(); // Assigning array to fetch the primary key: Serial Number
while($row = $fetchresult->fetch_assoc()){
$serialnumber[] = $row["sno"];
}
//Newly Inserted Values
//$_POST['sno'] is taken from the dynamic input field defined earlier in this post.
//Basically what we are doing here is we are comparing (the values
//which have been posted from the primary page) and (values present in the db table).
//The difference will give an array of newly inserted table input field values
$insert = array_diff($_POST['sno'],$serialnumber);
//Deleted Values
// This will Difference those values in the db table and values which are
// deleted from the primary dynamic table page
$delete = array_diff($serialnumber,$_POST['sno']);
$countdelete = count($delete); // Counting how many values have been
// lined up for deleting
//Updated Values
// array_intersect will give us the common values present in both the array.
// This means that there is no deletion or insertion to the dynamic table fields.
$intersect = array_intersect($serialnumber, $_POST['sno']);
$update = array_values($intersect);
$countupdate = count($update);
//INSERT ADDED VALUES TO DB
foreach($insert as $key=>$ivalue){
// ID
if(isset($_POST['id'][$key]) && !empty($_POST['id'][$key])) {
$id = strip_tags(trim($_POST['id'][$key]));
}
// ITEM
if(isset($_POST['item'][$key]) && !empty($_POST['item'][$key])) {
$item = strip_tags(trim($_POST['item'][$key]));
}
// DESCRIPTION
if(isset($_POST['description'][$key]) && !empty($_POST['description'][$key])) {
$description = strip_tags(trim($_POST['description'][$key]));
}
// UNITCOST
if(isset($_POST['unitcost'][$key]) && !empty($_POST['unitcost'][$key])) {
$unitcost = strip_tags(trim($_POST['unitcost'][$key]));
}
// QUANTITY
if(isset($_POST['qty'][$key]) && !empty($_POST['qty'][$key])) {
$qty = strip_tags(trim($_POST['qty'][$key]));
}
// AMOUNT
if(isset($_POST['amount'][$key]) && !empty($_POST['amount'][$key])) {
$amount = strip_tags(trim($_POST['amount'][$key]));
}
// INSERT INTO THE DATABASE
$inserttable = $link->prepare("INSERT INTO product (productid, item, description, unitcost, qty, amount) VALUES(?,?,?,?,?,?)");
$inserttable->bind_param('ssssss', $id, $item, $description, $unitcost, $qty, $amount);
$inserttable->execute();
if($inserttable){
header( 'Location:to/your/redirect page.php' ) ; // NOT MANDADTORY, You can put whatever you want
$_SESSION['updatemsg'] = "Success";
}
}
//UPDATE EXISTING VALUES TO DB
for($j=0; $j<$countupdate; $j++){
// ID
if(isset($_POST['id'][$j]) && !empty($_POST['id'][$j])) {
$uid = strip_tags(trim($_POST['id'][$j]));
}
// ITEM
if(isset($_POST['item'][$j]) && !empty($_POST['item'][$j])) {
$uitem = strip_tags(trim($_POST['item'][$j]));
}
// DESCRIPTION
if(isset($_POST['description'][$j]) && !empty($_POST['description'][$j])) {
$udescription = strip_tags(trim($_POST['description'][$j]));
}
// UNITCOST
if(isset($_POST['unitcost'][$j]) && !empty($_POST['unitcost'][$j])) {
$uunitcost = strip_tags(trim($_POST['unitcost'][$j]));
}
// QUANTITY
if(isset($_POST['qty'][$j]) && !empty($_POST['qty'][$j])) {
$uqty = strip_tags(trim($_POST['qty'][$j]));
}
// AMOUNT
if(isset($_POST['amount'][$j]) && !empty($_POST['amount'][$j])) {
$uamount = strip_tags(trim($_POST['amount'][$j]));
}
// UPDATE THE DATABASE
$updatetable = $link->prepare("UPDATE product SET item=?, description=?, unitcost=?, qty=?, amount=? WHERE sno=?");
$updatetable->bind_param('ssssss', $uitem, $udescription, $uunitcost, $uqty, $uamount, $update[$j]);
$updatetable->execute();
if($updatetable){
$_SESSION['updatemsg'] = "Success";
}
}
//DELETE VALUES FROM DB
foreach($delete as $sno){
$deletetable = $link->prepare("DELETE FROM product WHERE sno=?");
$deletetable->bind_param('s', $sno);
$deletetable->execute();
if($deletetable){
$_SESSION['updatemsg'] = "Success";
}
}
}else {
$_SESSION['updatemsg'] = "Error";
}
}

how to explode array with certain key in php

I'm developing an app about books and I had a table for contents. before, I made a mistake and I split content in myself and insert them in database. after inserting 90 books I had 1000 records and I found out that it was wrong. Now, I create a table of content and I insert all content of every books(every book has a record), so I want to split content with character(*).
but it doesn't work.
It is my Previous code:
$sql2 = "SELECT tblcontent.content
from tblcontent,tblstory
where tblcontent.storyid=tblstory.storyid
and tblcontent.storyid='$storyid'";
$r2 = #mysqli_query($dbLink,$sql2);
$result2 = array();
while($res2 = #mysqli_fetch_assoc($r2))
{
$result2[] = $res2;
}
and I've added this code:
$result2=explode("*",$result2);
and
if(isset($result2)){
echo json_encode(array("result2"=>$result2));
}
But it doesn't work.Thanks in advance

Duplicate a row in sql table

With the code below, im trying to duplicate a product row with ajax in a webshops table, named termek.
If the last product is ID 90, and i copy this, the new product will be ID 91.
Sometimes, and i dont know why, the ID 90(what i copyed), loose the image, the thumb and big cell in the table, or it is renamed or i dont know what going on.
Is this code okay for copying, or whats wrong whit it?
<?php
include_once("../../files/connect.php");
if(!empty($_POST))
{
$id = mysqli_real_escape_string($kapcs, $_POST['id']);
$sql =
"
INSERT INTO termek
(
termek_nev,
termek_seo,
termek_rovid,
termek_hosszu,
termek_thumb,
termek_big,
termek_seo_title,
termek_seo_rovid,
termek_seo_kw,
termek_status,
termek_view,
termek_akcio,
termek_normal_ar,
termek_akcios_ar,
termek_cikkszam,
termek_egyseg,
termek_fooldal,
termek_kiemelt,
termek_suly,
termek_keszlet_db,
termek_keszlet_warning,
termek_min_order,
termek_allapot,
termek_gyarto,
termek_jobb_arat_btn,
termek_tipus,
termek_szavak
)
SELECT
termek_nev,
termek_seo,
termek_rovid,
termek_hosszu,
termek_thumb,
termek_big,
termek_seo_title,
termek_seo_rovid,
termek_seo_kw,
termek_status,
termek_view,
termek_akcio,
termek_normal_ar,
termek_akcios_ar,
termek_cikkszam,
termek_egyseg,
termek_fooldal,
termek_kiemelt,
termek_suly,
termek_keszlet_db,
termek_keszlet_warning,
termek_min_order,
termek_allapot,
termek_gyarto,
termek_jobb_arat_btn,
termek_tipus,
termek_szavak
FROM termek WHERE termek_id = '$id'
";
if(mysqli_query($kapcs, $sql))
{
echo (int)1;
}
else
{
echo mysqli_error($kapcs);
}
}
?>
To solve the problem, i uploaded a noimage.jpg to the products folder. When im editing the copied or the old product and changing its image, i dont delete the old image, if the thumb or big column == noimage.jpg.
Sorry for bad english.

PHP mySQL JOIN with matching column names

Noticed a rather large problem. When I join two tables togeter the fact that there is a column called ID in both of them causes the wrong tables ID to be used in a PHP equasion later on.
The simple solution would be to change the column name, but there are other standards thoughout the database too including columns called name in every table and title in many of them.
Is there a way around this or should I rename the entire database to ensure that there are no duplicate columns.
THE CODE FOR REFERENCE
$criteria = "SELECT *
FROM voting_intention,electors
WHERE voting_intention.elector = electors.ID
AND electors.postal_vote = 1
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
AND electors.telephone > 0"
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria"); while($row = mysql_fetch_array($the_elector)) {
return $row['ID']; }
While "Gunnx" solution is perfectly acceptable, I'd like to present an alternative since you appear to be using only the ID column of the result.
SELECT
electors.ID
FROM
voting_intention,electors
....
I wrote this function to assist in doing this. Basically it prepends the table name to the fields name of an associated array.
while($row = mysql_fetch_array($the_elector))
{
return $row['ID'];
}
would become
while($row = mysql_fetch_table_assoc($the_elector))
{
return $row['voting_intention.ID'];
}
function:
function mysql_fetch_table_assoc($resource)
{
// function to get all data from a query, without over-writing the same field
// by using the table name and the field name as the index
// get data first
$data=mysql_fetch_row($resource);
if(!$data) return $data; // end of data
// get field info
$fields=array();
$index=0;
$num_fields=mysql_num_fields($resource);
while($index<$num_fields)
{
$meta=mysql_fetch_field($resource, $index);
if(!$meta)
{
// if no field info then just use index number by default
$fields[$index]=$index;
}
else
{
$fields[$index]='';
// deal with field aliases - ie no table name ( SELECT T_1.a AS temp, 3 AS bob )
if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
// deal with raw data - ie no field name ( SELECT 1, MAX(index) )
if(!empty($meta->name)) $fields[$index].=$meta->name; else $fields[$index].=$index;
}
$index++;
}
$assoc_data=array_combine($fields, $data);
return $assoc_data;
}
?>
mysql_fetch_row will get the data as a numerical array

Possibly simple PHP/MYSQL issue with retrieving and showing data

I have been racking my brains over this for a while now. Here is the data I have in the SQL data base as an example:
ID | TYPE | DATA
1 | TXT | TEST
2 | PHP | php
3 | JS | JAVASCRIPT
That is just an example, there are multiple listing for TXT, PHP and JS throughout the table. What I want to do is retrive all the data and display it all into separate drop down/select boxes. Meaning, select box one would list all data with type TXT, select box two would list all data with type PHP and select box 3 would list all data with type JS. The only way I have came about doing this is doing individual sql queries for each different type. I know there is a way to do it all in 1 query and then display it the way I want to but I just can't seem to figure out how and I know its going to drive me nuts when someone helps and I see just how they did it.
The only way that I know of to get all of the data in one query is just to do a generic SELECT * FROM tbl, and then you can group them in the code:
$res = mysqli_query('SELECT * FROM tbl');
$data = array();
while($row = mysql_fetch_assoc($res)) {
$type = $row['type'];
$data[$type][] = $row;
}
// $data contains all of the record, grouped by the TYPE column
foreach($data as $type => $records) {
echo "records for $type: <select>";
foreach($records as $record) {
echo "<option value='$id'>$id</option>";
}
echo "</select>";
}
Just retrieve all records and loop through them using PHP. Use an iterator if the recordset is going to be huge to prevent using too much memory.
$lists = array();
foreach($recordset as $record) {
$lists[$record['type']][$record['id']] = $record['data'];
}
Know you have an array containing all data.
Just order it by Type and make a loop using "foreach" into the results, changing of select box when the type is different than the preivous.
In this way you only loop once over the array.
You can do kind of grouping with "ORDER BY TYPE":
SELECT id, data
FROM table
ORDER BY type;
Then, in data output loop you can track current type, and build another select box once type changed:
$currentType = "no type";
while($row = mysql_fetch_assoc($res)) {
if ($currentType != $row['type']) {
$currentType = $row['type'];
// start new select box here
}
// do some other work here
}
BTW, such approach looks like kind of hack :)

Categories