This is my first post. on to the point
I am trying to make a bulk update in a MySQL table using a php if statement.but since i have no clue of mysql apart to connect to a database and update things 1 by 1.
So basically i am trying to use this if statement that is loooking for the word Casio in the name and avoids all prodcuts that have Bulgarian letters in the name on its own the code works,i just have 0 idea how to impliment it for MySQL would love some help to how to start.
<?php
require("words.php");
$product = "CASIO EF-513D-5AV MTP Chronograph";
if (strstr($product,"CASIO",0)) {
/*Watches for men*/
if (strstr($product,$gs,0) || strstr($product,$edifice,0) || strstr($product,$mtp,0) || strstr($product,$mrw,0)) {
if ($product == substr($avoid[0],0) || $product == substr($avoid[1],0) || $product == substr($avoid[2],0)) {
echo $product;
}
elseif(strstr($product,$gs,0)) {
echo str_replace($gs,$gsW,$product);
}
elseif(strstr($product,$edifice,0)) {
echo str_replace($edifice,$edificeW,$product);
}
elseif(strstr($product,$mtp,0)) {
echo str_replace($mtp,$mtpW,$product);
}
elseif(strstr($product,$mrw,0)) {
echo str_replace($mrw,$mrwW,$product);
}
}
}
/*Watches for women*/
elseif (condition) {
# code...
}
else{
}
?>
all the variables that the if statement above contains
<?php
/*Real words that we have*/
$gs = "G-SHOCK";
$casio = "CASIO";
$edifice = "EDIFICE";
$mtp = "MTP";
$mrw = "MRW";
/*Words that will be added*/
$gsW = "Мъжки спортен G-SHOCK";
$casioW = "часовник CASIO";
$edificeW = "Мъжки часовник EDIFICE";
$mtpW = "Мъжки часовник MTP";
$mrwW = "Мъжки часовник MRW";
/*Avoid words*/
$avoid = array("Мъжки","часовник","спортен")
?>
update:My idea is to target a table "product" and access the sub table "name" and which ever name has the word Casio in it,to start doing the if statement for it
Ok so far i've been searching far and wide and the only thing that i am missing is and If else statement
I've figure out how to search inside a table for a string with
$sql = "UPDATE product_description SET name = REPLACE(name, 'CASIO', 'Мъжки часовник CASIO')";
I Just don't how to to tell the code If you see $avoid don't do anything to those names but for the rest add which ever thing i specify
I think you just need to limit the SELECT by using a suitable WHERE clause.
WHERE name NOT LIKE '%Мъжки%' AND name NOT LIKE '%часовник%' AND name NOT LIKE '%спортен%'
You can construct the where clause in PHP along the lines of...
$where = "name NOT LIKE '%".implode("%' AND name NOT LIKE '%",$avoid).%'"
HTH
Make a backup of the original $product string.
<?php
$originalProduct = $product;
// Then your changes are to be made here
// Having finished modifying
$connection = mysqli_connect("localhost", "root", "", "database", 3306);
if($connection->connect_error)
{
// error occured while trying to connect to the database
}
else
{
$query = $connection->query("UPDATE `tablename` SET productName = '$product' WHERE productName = '$originalProduct' LIMIT 1;");
if($query)
{
// Successfully modified record
}
else
{
// error occured while trying to modify
}
}
?>
I think i found an answer to my own question
I could just use several of
$sql = "UPDATE product_description SET name = REPLACE(name, 'EDIFICE', 'Мъжки часовник EDIFICE');";
I am just not sure if it's a good idea to use several of those Replace statements
Related
I am trying to create a search facility for a website. the website contains text posts so the database has a table post_record with field post_id, post_title, post_href and post_content.
now the working is when a user enters any search keyword in search field, that keyword is being tested against all the post titles and post contents and where it matches it should return all those rows. Following is the code for it. the issue is its returning only the last row of the databse.
<table class="s_table">
<?php
require_once'config.php';
if(isset($_POST['search_btn']))
{
$mes = " ";
$search_key =" ";
$search_key = ($_POST['search_field']);
try
{
if(empty($search_key) && $search_key != " ")
{
echo $mes = "Enter the keyword you want to search.";
}
else
{
$result = $conn->prepare("SELECT * FROM post_record WHERE post_title LIKE '%".$search_key."%' OR post_content LIKE '%".$search_key."%'");
$result->execute();
$count=$result->rowCount();
$datas = $result->fetchAll();
if(!$count)
{
echo $mes = "No Result found. Try another keyword for search.";
}
else
{
foreach ($datas as $data)
{
echo "
<tr><td><b><u><a href='".$data['post_href']."'>".$data['post_title']."</a></b></u></td></tr><br>
<tr><td class='s_cont'>".$data['post_content']."</tr></td><br><br>";
}
}
}
}
catch(PDOException $e)
{
$mes = "Something Went Wrong! try again";
header("location:index.php");
}
}
$conn = null;
?>
Everything is working fine except the thing that it is displaying only last row of the database.
Right now database has 3 posts and for testing purpose i tried a keyword that i know is common in all the post contents but its not working. only last row the database is being fetched and tested.
if(empty($search_key) && $search_key != " ") this condition is wrong
Both are different things which wont get true ever.
you are testing if its empty and then u r testing if its not empty
Both in same if condition
I usually use procedual functions but I encounter a problem like this with the mysqi_fetch_array(), so your problem might be that fetchAll() is moving the cursor to the last record. Try to remove that function or use mysql_data_seek($datas , 0) before the foreach() .
I am trying to do a search on my website but for some reason my SELECT query is swapping the keyword and name of the column name when it is executed. Below is code for my query:
if(empty($_POST)=== false){
$output = '';
$error = '';
$input = $_POST['search_input'];
$i=0;
if($input){
$keyword = explode(" ", $input);
require ('core/dbconnection.php');
//If a user is logged in check if the user is Admin or Customer.
if(isset($_SESSION['userid'])){
if($admin == 1){
//enter admin code here
}
}else{
//If user is not logged in search items table only.
$search_items = "SELECT * FROM fyp_items WHERE ";
foreach($keyword as $k){
$i++;
if($i == 1){
$search_items .= "name LIKE $k OR description LIKE $k";
}else
$search_items .= " OR name LIKE $k OR description LIKE $k";
}
$item_qry = mysql_query($search_items)or die(mysql_error());
}
}else
$error = '<p class="pageerror">Please enter your search terms.</p>';
The $search_items is concatanating the search query which is then executed by $item_query .
So I searched for "conwerse" and echo'ed out the $search_itemsvariable I got the following:
http://awesomescreenshot.com/0302ft5mc3
However, when I run the query I get this mysql_error...
http://awesomescreenshot.com/0552ft6bb4
Seems like it swaps the keyword and column name when I run the query. My database tables are of type InnoDB> I would much appreciate your help!
First of all, dont use mysql_query as all mysql_ functions are deprecated. Use mysqli or pdo.
Second, escape your keywords with mysql_escape_string();, like
$k = mysql_real_escape_string($k);
Third, your query, when you echo it, needs to look like this:
SELECT * FROM fyp_items WHERE `name` LIKE 'conwerse' OR `description` LIKE 'conwerse';
There is more, but this should get you started.
I've started making a Video script that loads the videos using MySql and I am using Mysqli.
However, There's 2 Rows that it should post, but it only post the second none, not the first one.
It loads the results using "Brand" so if there's 2 rows named "Test", it only loads the second one, but not the first one.
So, what is causing this? I've tried with 3 rows, and it did not include the first row.
Code
<?php
{ /* Global Data */
ini_set('display_errors', 0);
ini_set('error_reporting', -0);
$GetPath = $_GET['b'];
$SqlUser = "root";
$SqlPass = "**Private**";
$SqlHost = "localhost";
$SqlData = "heisteknikk";
}
{ /* Mysql Connect */
$Sql = new mysqli($SqlHost, $SqlUser, $SqlPass, $SqlData);
if ($Sql->connect_error) { die("Sorry, Could not connect (".$Sql->connect_errno.") ".$Sql->connect_error);}
}
{ /* Test */
$Brand = $Sql->real_escape_string($GetPath);
$SqlData = "SELECT * FROM videos WHERE Brand = '".$Brand."'";
$SqlQuery = $Sql->query($SqlData);
if (!$SqlQuery) {
echo $Sql->error;
}
if ($SqlQuery->num_rows == 0) {
die("Nothing was found");
}
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
echo "
<tr><td>".$Heis['Brand']."</td><td>".$Heis['Name']."</td><td>".$Heis['Location']."
";
}
echo "</table>";
$Sql->close();
}
?>
This line causes the bug:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
With this line you effectively throw out the first row of the result set, as you don't process $Data at all in the code below. Just remove it, and your script should work fine (I assume that closing </td></tr> sequence was lost when pasting the code, am I right?)
Comment out (or better yet, remove) this line:
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
It is grabbing the first row...then you aren't doing anything with $Data and then grabbing the second (and consecutive rows) for display in your while loop. Commenting out that line above will make your loop grab and display them starting at the first one.
In your code
$Data = $SqlQuery->fetch_array(MYSQLI_ASSOC);
echo "<table border='1'>";
while ($Heis = $SqlQuery->fetch_assoc()) {
you're fetching a row (with fetch_array), throwing it away and then fetching another row (with fetch_assoc). That's probably why you're only seeing one row instead of two
I have an issue in a PHP script which checks if the tax number has right company name on input some other form fields and insert into MySQL. What I want is to put some control code - maybe "select distinct formCompany from company where formCompany = ".$formCompany." " or some code which checks if taxid is given correctly for the name of company from input form. Does someone have idea of how to do that? Any example is welcome.
I have script which simply input data from form fields into MySQL db:
$db=mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db);
$taxid=mysql_real_escape_string($_POST['taxid']);
$formCompany=mysql_real_escape_string($_POST['formCompany']);
$formOffice=mysql_real_escape_string($_POST['formOffice']);
$formBr=mysql_real_escape_string($_POST['formBr']);
$formContact=mysql_real_escape_string($_POST['formContact']);
//trim
$id=trim($id);
$taxid=trim($taxid);
$formCompany=trim($formCompany);
$formOffice=trim($formOffice);
$formBr=trim($formBr);
$formContact=trim($formContact);
if($_POST['taxid']==''||$_POST['formCompany']=='') {
echo '<p style="color: red">Input relevant data!<p>';
} else {
$sql = "INSERT INTO company (taxid, formCompany,formOffice,formBr,formContact) VALUES ('$taxid','$formCompany','$formOffice','$formBr', '$formContact')";
if(!$result = mysql_query($sql, $db)) {
echo "ERROR: ".mysql_error();
} else {
header("Refresh: 0; url=main.php");
}
}
First, add this code before the if statement
$taxcheck = mysql_query("SELECT * FROM company WHERE taxid = '" . $taxid . "' ");
if (mysql_num_rows($taxcheck)) { $exists = true; }
else { $exists = false; }
Then change this line
if($_POST['taxid']==''||$_POST['formCompany']=='')
to
if($_POST['taxid'] == "" || $_POST['formCompany'] == "" || $exists == true)
This code will prevent you from ending up with more than one company using one tax ID number.
From what I understand, two companies - formCompany - in your app cannot have the same tax-id - taxid, right? If yes, the simplest way is to create a unique index on company.taxid. Any attempt then to insert another company with the same tax-id will thrown a MySQL error.
Here is the query for adding the unique index:
ALTER TABLE `company` ADD UNIQUE INDEX `idx_u_taxid` (`taxid`);
Hope it helps!
I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.