Copy column values to another column in the same table - php

I'm trying to copy title column to keywords column in database, so the keywords will be inserted automatically from the title.
http://store2.up-00.com/2015-06/1435609110941.png
I want to add comma ', ' before each word for example.
" It's my first program "
it will turn into
" It's, my, first, program, "
This the code I wrote.
<?php
// $id =mysql_insert_id;
$select_posts = mysql_query("SELECT * FROM `posts`");
while($row = mysql_fetch_array($select_posts)){
$id = $row['post_id'];
$text = $row['post_title'];
$delim = ' \n\t,.!?:;';
$tok = strtok($text, $delim);
while ( $tok !== false){
echo $tok1 = $tok.',';
mysql_query("UPDATE `posts` SET `post_keywords` = '$tok1' WHERE `post_id` = $id ");
$tok = strtok($delim);
}
}
?>
it insert the last word in each title column , because the words is overwritten by while loop.
Please help me .

Concat the values:
... SET post_keywords = CONCAT(post_keywords, '$tok1')
and note that you're vulnerable to sql injection attacks. Just because that $tok1 value came out of a database doesn't mean it's safe to REUSE in a query...

You can do it with a single query :
UPDATE `posts` SET post_keywords = REPLACE(post_title, ' ', ',');

Related

A way to skip over a row if it has already been displayed

I have a search script that retrieves an integer from one table and uses it to search through the IDs of a 2nd table. My issue is if the integer in Table1 appears more then once, I get duplicate results when querying Table2.
Does anyone know a way to use SQL or PHP so that if a row is already displayed it will skip it? Thanks
My code is rather convuleted but here it is if it helps:
//TV FILTERS
$sql = 'SELECT * FROM `table1`';
$where = array();
if ($searchlocation !== 'Any') $where[] = '`value` LIKE "%'.$searchlocation.'%"';
if ($searchmake !== 'Any') $where[] = '`value` LIKE "%'.$searchmake.'%"';
if ($searchtype !== 'Any') $where[] = '`value` LIKE "%'.$searchtype.'%"';
if (count($where) > 0) {
$sql .= ' WHERE '.implode(' OR ', $where);
} else {
// Error out; must specify at least one!
}
$tvqresult = mysql_query($sql);
$num_rowstvq = mysql_num_rows($tvqresult);
while ($rowtvq = mysql_fetch_array($tvqresult)) {
$contid = $rowtvq['contentid'];
//MAIN QUERY
$mainsql = 'SELECT * FROM `table2` WHERE `content` LIKE "%' . $searchterm . '%" AND `id` = ' . $rowtvq['contentid'] . ' AND `template` = 12';
$resultmain = mysql_query($mainsql);
$num_rowsmain = mysql_num_rows($resultmain);
if (!$resultmain) {
continue;
}
else {
while ($row = mysql_fetch_array($resultmain )) {
echo "[!Ditto? &parents=`134` &documents=" . $row['id'] . "&tpl=`usedtempchunk`!]";
}//END MAIN LOOP
}//END MAIN ELSE
}//END TV WHILE LOOP
You only seem to use the contentid column from your first query, so you could change it to:
$sql = 'SELECT distinct contentid FROM `table1`'; // rest would be the same
which would mean that no duplicates will be retreived saving you any hassle in changing your second set of code.
If you are using other columns from the first query somewhere else in your code, you can still fetch more columns with this method as long as there are no duplicate IDs:
$sql = 'SELECT distinct contentid, contentTitle, contentThing FROM `table1`';
If you have to have repeated IDs in your original query, I think you will have to store the data in a variable (like an array) and then make sure that the second dataset isn't repeating anything.
It sounds like you're only looking for 1 row, if so, then at the end of your SQL, simply add LIMIT 1. That'll ensure you only return 1 row, thereby ignoring any duplicate matches.

insert new rows from db1.table1 into db2.table1

I have two databases($db1, $db2) with exact table structure(table1). $db2.table1 has new rows which i want to insert into $db1.table1 (i.e. if $db2 is new and $db1 is old, I want to update $db1 with new entries from $db2).
I came up with following php code, and it should work fine, but I am worried about special characters in column ids as well as values to be inserted in it.
Here's the code:
require('update_functions.php'); //contains helper functions
function arraywalk_mysql_real_escape_string(&$value, &$key, $sql_connection) {
$value = mysql_real_escape_string($value, $sql_connection);
$key = mysql_real_escape_string($key, $sql_connection);
}
$sql_connection_old = connectdb('old');
$sql_connection_new = connectdb('new');
$table = 'member'; $pkey = 'id'; //table name and primary key
$last_row_member = mysql_fetch_assoc(last_row($sql_connection_old, $table, $pkey));
//fetches last row from old db
$new_row = new_row($sql_connection_new, $pkey, $last_row_member[$pkey], $table, 'ASC LIMIT 1');
//the new_row function executes following query (after sanitizing input)
//'SELECT * FROM '.$table.' WHERE '.$pkey.'>'.$pkey_value.' ORDER BY '.$pkey.' '.$extra
while($result = mysql_fetch_assoc($new_row)) {
array_walk($result, 'arraywalk_mysql_real_escape_string', $sql_connection_old);
$update_member_query = 'INSERT INTO ' . $table . '( '
. implode(", ", array_keys($insert_vars))
. ' ) VALUES ( \''
. implode("', '", $insert_vars)
. '\' )';
}
I don't know if there will be any special characters in column names. Should I enclose them in backticks?
If yes then should I parse them using mysql_real_escape_srting()?
What about VALUES ? Should I enclose them in quotes 'value'? What if the value to be inserted is a number? what if its Date/Time?
Is there a way where I can bypass fetching data from old database into PHP variables and inserting it back to database (so above questions become irrelevant)?
Note : Even though there are two connections, I have the same SQL server serving the two $db
You can do it in SQL:
INSERT INTO db1.table1
SELECT * FROM db2.table1
WHERE db2.table1.id > (SELECT MAX(id) FROM db1.table1)

mysql update, computer says it works but no change in database

<?php
require('dbconnect.php');
$indexno = $_POST['indexno'];
$cevap = $_POST['cevap'];
$cevapdate = gmdate("Y-m-d\TH:i:s\Z");
$query = "UPDATE soru
SET cevap = '$cevap',
cevapdate = '$cevapdate'
WHERE `index` = '$indexno'";
$link = mysql_query($query);
if(!$link) {
die('not worked: ' . mysql_error());
} else {
mysql_close($con);
echo 'worked';
}
?>
Outcome of this php code is "Worked." but there is no change in the database. The thing is Im trying to update the cevap and cevapdate fields on a row by index id.
You need to remove the single quotes from aroud the index. You should not put single quotes around a column name while writing a query. Write your query this way -
$query = "UPDATE soru SET cevap = '$cevap', cevapdate = '$cevapdate' WHERE index = '$indexno'";
You have to escape your rows/table with backticks, not single-quotes.
$query = "UPDATE `soru`
SET `cevap` = '$cevap', `cevapdate` = '$cevapdate'
WHERE `index` = '$indexno'";
Also, you should escape your user input to prevent SQL injections.

SQL LIKE query to match any single word in a string

I am trying to query:
$title2 = (isset($row_DetailRS1['r_bus_name']) ? $row_DetailRS1['r_bus_name'] : "");
$query_test = "SELECT *
FROM table
WHERE r_email = '$email2'
AND r_city != '$location2'
AND r_bus_name LIKE '%$title2%'
ORDER BY r_bus_name";
The r_bus_name LIKE '%$title2' is defined from above and is grabbing the TITLE of the EVENT from the POST. The title is usually two to three words...
How do I query r_bus_name LIKE (any of the words in the event title $title2)?
Because right now it is taking the whole value of $title2.. I need to split them up or explode them in words, so if the title is something like "Test title here" then "Tester title here" would match?
If you want to search on EACH of the words in the title, you would need to construct a query using OR operations to apply them to the same query.
It might look something like this:
// break apart the title using spaces
$title2 = (isset($row_DetailRS1['r_bus_name']) ? $row_DetailRS1['r_bus_name'] : "");
$title_keywords = explode(" ", $title2);
// construct conditions (Note the ampersand causes pass-by-reference)
foreach($title_keywords as &$keyword) {
$keyword = "r_bus_name LIKE '%".mysql_real_escape_string($keyword)."%'";
}
$keyword_search = "(" . implode(" OR ", $title_keywords) . ")";
$query_test = "SELECT *
FROM table
WHERE r_email = '".mysql_real_escape_string($email2)."'
AND r_city != '".mysql_real_escape_string($location2)."'
AND ".$keyword_search."
ORDER BY r_bus_name";
// ...
Assuming the table is MyISAM, you could use the native Full Text Search (FTS) functionality:
$query = sprintf("SELECT t.*
FROM YOUR_TABLE t
WHERE t.r_email = '%s'
AND t.r_city != '%s'
AND MATCH(t.r_bus_name) AGAINST('%s')
ORDER BY t.r_bus_name",
mysql_real_escape_string($email2),
mysql_real_escape_string($location2),
mysql_real_escape_string($title2) );
$result = mysql_query($query);
Sadly, MySQL doesn't support FTS on the InnoDB engine.
Addendum
I recommend using sprintf if you aren't using PDO/etc for prepared statements, to protect against SQL injection attacks.
Split title2 on spaces and do multiple likes:
$titleArray = split(" ", $title2);
$query_test = "SELECT *
FROM table
WHERE r_email = '$email2'
AND r_city != '$location2'
AND ("
foreach ($title as titleArray)
$query_test .= "OR r_bus_name LIKE '%$title%'"
$query_test .= "ORDER BY r_bus_name";

The Select query I am using is not working.. Can Somebody Guide me to the Correct way?

I am using the Select query as
SELECT id, ordering FROM `jos_menu` WHERE ordering='".$rec['ordering'] -'1' ."' AND parent = '0'
Here I need all the records whose ordering is less than 1 of the selected record's order($rec['ordering'] = getting from other select query ) when I am trying to echo the query I am not getting complete statement but getting only this -1' AND parent = '0'
here is the whole snippet
$where = ' WHERE (id = ' . implode( ' OR id = ', $cid ) . ')';//Pranav Dave Coded
echo $selquery = "SELECT id, ordering FROM `jos_menu`".$where; //Pranav Dave Coded
$db->setQuery( $selquery );//Pranav Dave Coded
$record = $db->loadAssocList(); //Pranav Dave Coded
if ($model->orderItem($id, -1)) {
echo "<pre>";
print_r($model);
/*exit;*/
//echo $updorderup = mysql_escape_string($model->_db->_sql);//Pranav Dave Coded
foreach($record as $rec)//Pranav Dave Coded
{
echo $aboverow = "SELECT id, ordering FROM `jos_menu` WHERE ordering='".$rec['ordering'] -'1' ."' AND parent = '0'";
$db->setQuery( $aboverow );
$above = $db->loadAssoc();
echo "<pre>";
print_r($above);
}//end of foreach
}//end of if
Please suggest me where I am getting wrong.....
It looks like you may need to unwrap the -1 from the quotes:
WHERE ordering='".($rec['ordering'] - 1)."' AND parent = '0'";
Why do you trying to put everything inline?
Why not to make some preparations first?
Why not to compare resulting query with sample one?
Why don't you check every step if it return proper result?
$val = $rec['ordering'] - 1;
//let's see if $cal has proper value:
echo $val."<br>";
$sql = "SELECT id, ordering FROM `jos_menu` WHERE ordering = $val AND parent = 0";
//let's see if query looks good:
echo $sql;
//let's print sampe query to compare:
echo "<br>" ;
echo "SELECT id, ordering FROM `jos_menu` WHERE ordering = 1 AND parent = 0";
As Daniel said, you need to remove the quotes around the -1. Currently its trying to minus a string, which it wouldn't be happy with at all ;)

Categories