How can you perform a search and replace with php on an array returned from mysql_fetch_array()? If I use preg_replace() it will not return a match. Is there something that I'm missing?
This is what I have used without sucess, could anyone pleas take a look and tell me what I'm doing wrong, or possibly a better way to achive this:
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db(DATABASE_NAME)
or die("<p>Error selecting the database " . DATABASE_NAME . mysql_error() . "</p>");
$sql = "SELECT product_id,description FROM oc_product_description WHERE product_id >= 97 AND product_id <= 100";
$result = mysql_query($sql);
$pattern = '/^.*\b([0-9]{6}\s\D\d|[0-9]{6}\s\D[0-9]{2}|[0-9]{7}\s\D[0-9]{2})\b.*$/';
$replace = '$1';
while($row = mysql_fetch_assoc($result))
{
$item[] = $row['description'];
}
foreach($item as $items)
{
echo preg_replace($pattern, $replace, $items) . '<br>';
echo '<br>';
}
all that this will do is return the same as it would without the preg_replace(). Now I know the code works because if I output a print_r($item) and copy the results into an array it works just fine. Am i doing something wrong or does preg_replace() just not work with arrays returned from mysql_fetch_assoc or mysql_fetch_array? I could put my example up where i copy the results into an array but dont want to waste space. Here is an example of an item returned from the database and the string I'm trying to match with regex. I need everything removed but the match.
One item returned from $row['description']:
1997 Suzuki VZ800 Marauder, Engine # 5506-111789, Kick stand and spring. Chrome on end is starting to chip. 0121103 S19 <img src = ">http://www.roofis27.com/motorcycle/13_01_21/103.JPG">
Here is what the regex retrurns: 0121103 S19
So therefore I have over 20,000 entry's in a database with descriptions like these and need these codes like the example above removed from them so I can INSERT them into another table column that matches the product_id relational to the descriptions product_id. I am not the best with SQL, but the <img> tag is always after the code so maybe there is a way to do it with SQL that I'm not aware of? My main concern at this point is why preg_replace() doesn't work with an array returned from mysql_fetch_array(), but works fine on any other arrays ( associative, multidimensional or not). Is there something about the values returned from a database that prevent me from being able to do this? Anything would be greatly appreciated, I'm really stuck on this!
After thinking about what jerry had to say(in the comment above) I came up with this resolution, apparently there are characters in the return from mysql_fetch_array() that are invisible and that's why the regexp does not work. I got way better results using preg_match() as follows:
$sql = 'SELECT product_id,description FROM oc_product_description';
$sql1 = 'UPDATE db_product SET model = ';
$sql2 = 'WHERE product_id = ';
$pattern = '([0-9]{6}\s\D[0-9]{2}|[0-9]{6}\s\D\d|[0-9]{7}\s\D[0-9]{2})';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$data[] = $row['description'];
foreach($data as $datas)
{
preg_match($pattern, $datas, $matches, PREG_OFFSET_CAPTURE);
}
foreach($matches as $match)
{
$Q1 = $sql1 . '"'. $match[0] . '"' . ' ';
}
$Q2 = $sql2 . $row['product_id'] .';';
$query = $Q1 . $Q2;
mysql_query($query);
echo 'Product ID' . $row['product_id'] . ': ';
printf("Records updated: %d\n", mysql_affected_rows());
echo '<br>';
}
Yes, I will start using PDO for database cons and querys, did some research on it and look pretty cool. It's just I'm new to php and still in school so I have so much learning going on I hate having to change ( better get used to it though, HUH?) Thank you jerry :)
Related
// This gets all the users that are active
// The limit is completely random, it is set to 2 for this example
$sql = <<<SQL
SELECT *
FROM `accounts`
WHERE active = 1
LIMIT 2
SQL;
if(!$getaccounts = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while ($row = $getaccounts->fetch_assoc()) {
$getid = $row["id"].',';
$getid = substr($getid, 0, -1);
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getid;
echo $getusername."<br>";
echo $getpassword."<br>";
}
I know this hasn't been prepared but I am not using it for anything other than personal use.
I cannot understand why this is not getting rid of the last comma?
The output may be something like "32,14,"
And I want to get rid of the last comma by using the "substr" function.
But the output that that I get from $getid is "3214" (It gets rid of all the commas instead of just the last one.
I need it to output "32,14" but it's not working?
Could someone please tell me where I am going wrong?
If I do rtrim, it does the same thing and gets rid of all the commas! I am going to update something in the database using the ids, and that is why I need to get rid of the last comma
And I know this code is not secure, I am not using it for anything other than personal use and I was hoping someone could help me figure this out, I have been attempting it for days, it seems really simple and I bet I am missing something really stupid!
You have a XY Problem.
You want to concat all the id's into a comma-seperated string.
Here's a much easier solution by adding the items to an array and then implode().
<?php
// rest of your code
$ids = Array();
while ($row = $getaccounts->fetch_assoc()) {
$ids[] = $row["id"];
$getusername = $row["username"];
$getpassword = $row["password"];
echo $getusername."<br>";
echo $getpassword."<br>";
}
echo "ids: " . implode(",",$ids);
You should write code like..
$getid = "";
while ($row = $getaccounts->fetch_assoc()) {
$getid .= $row["id"].',';
}
$getid = rtrim($getid,',');
$q = " UPDATE accounts SET active = '0' WHERE id IN ($getid) ";
$search = htmlspecialchars($_GET["s"]);
if(isset($_GET['s'])) {
// id index exists
$wordarray = explode(" ",$search);
$stringsearch = implode('%',$wordarray);
echo $stringsearch;
echo ",";
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
if (!empty($result)) {
echo sizeof($result);
echo ",";
Database has 3 rows with titles test,pest,nest with corresponding id's 1,2,3. when i request domain.com/?s=est
it echos something like this
est,2,
Now when i checked $result[0] and $result[1], $result[0] echoed 1 and $result[1] didn't echo anything. When I use foreach function, it is taking only value of $result[0]
and $result should be array of all the three indexes.
I cannot find any mistake,
when i type the same command in sql console it works, somebody help me, thanks in advance.
The problem is, if you're expecting multiple rows, then don't do this:
$result = mysqli_fetch_array($conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%';"));
This only fetches the first row, you need to loop it to advance the next pointer and get the next following row set:
$result = $conn->query("SELECT ID FROM table WHERE title LIKE '%$stringsearch%' ");
while($row = $result->fetch_array()) {
echo $row[0] . '<br/>';
// or $row['ID'];
}
Sidenote: Consider using prepared statements instead, since mysqli already supports this.
This is pretty straight forward.
EDIT: Updated question and added fourth echo.
Here is PHP code:
<?php
$ratings="3";
$item="Inception";
$query="SELECT * FROM items WHERE item = '". $item ."' LIMIT 1";
echo $query;
echo "<br />";
$result=mysql_query($query);
echo $result;
echo "<br />";
while ($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
echo $item_id;
echo "<br />";
}
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
echo $query_two;
$sql = mysql_query($query_two);
mysql_close();
?>
Here is web output with all the echo's:
SELECT * FROM items WHERE item = 'Inception' LIMIT 1
Resource id #7
INSERT INTO ratings (rating, item_id), VALUES (' 3 ', ' ')
How come my $item_id is blank? (third row underneath Resource id)
This part of code produces it:
$result=mysql_query($query);
echo $result;
It shows Resource... because it is of resource type, it's just a sort of special handler for query, it's not like normal type (string or int for example), so it has nothing readable to print.
If you want to print data from query then you must firstly fetch it.
Also note that those mysql_* functions are deprecated, it is discouraged to use them. Note from php manual:
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL
extension should be used. See also MySQL: choosing an API guide and
related FAQ for more information. Alternatives to this function
include:
mysqli_query()
PDO::query()
This does not have anything to do with IDs from the database.
This (Result#7) says that this result resource is seventh resource to be created by your php script execution.
Also
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
should be
$query_two = "INSERT INTO ratings (rating, item_id) VALUES (' {$ratings} ', ' {$item_id} ')";
You have comma before VALUES.
Also, it seems that $item_id is blank. Please check DB whether you have data for item = 'Inception'.
Regarding, Result#7 please follow others answers.
The Resource ID is coming from the actual process/object that the MySQL Query is.
to return the result you need:
$row = mysql_fetch_array( $query );
echo $row['item']
You need to do something with the result resource. Try this:
$result=mysql_query($query);
//echo $result;
$result_array = mysql_fetch_assoc( $result );
print_r( $result_array );
EDIT: I see you updated your question.
You should run your item='Inception' query directly in MySQL to confirm that results are what you expect.
You cannot echo the result that simple. You need to fetch the result to for example an array:
while ($row = mysql_fetch_array($query)) {
echo $row['a_column'] . "<br />";
}
or an object:
while ($variable = mysql_fetch_object($query) {
$value = $variable->a_column;
}
echo $value;
There are more ways but this is just two examples
I already have data I scraped from a web table and I've noticed some leading spaces and nbsp in some entries. I realize I should have cleaned the data while scraping before inserting it into MySQL but it was a while ago and I don't feel like repeating the process if I don't have to. I came up with this PHP script (late) last night and it works up until I try to update the entries.
<?php
require_once("login.php");
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database);
$query = "SELECT * FROM ingredients;";
$result = mysql_query($query);
$i = 1;
$e = array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
//echo $row[1];
$str = trim(mysql_real_escape_string($row[1]));
$e[] = $str;
$i++;
}
//print_r($e);
/*
$i = 1;
foreach($e as $entry) {
$query = "UPDATE ingredients
SET ing_name = $entry
WHERE ing_id = $i;";
mysql_query($query);
$i++;
}*/
?>
Couple of questions:
Is there a way to do this strictly in MySQL without using PHP?
What function/s should I use to strip the strings in order to convert to plaintext and remove all leading, trailing, and nbsp spaces?
The PHP script seems to work until updating the data, what gives?
Thanks
There's a large number of MySQL String Functions that can help with this sort of thing.
You might need a combination of REPLACE and TRIM to clean it up:
UPDATE table SET column=TRIM(REPLACE(column, ' ', ' '))
Also try not to use mysql_query, but use PDO instead. Writing queries directly leaves you exposed to SQL injection problems.
I think this will do it for you strictly with a SQL query:
UPDATE ingredients SET column_with_spaces = TRIM(column_with_spaces)
As far as future scraping goes, use trim() before inserting into the database.
If you are looking for a mysql solution for string trimming and replacing you should have a look at the mysql string functions found here:
Trim: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_trim
Replace: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace
//The PHP keyword <b>strtr()</b> is much easier to understand: <br>
$query = "SELECT * FROM ingredients";<br>
$query= strtr($isql, array(' ~;' => ' ')) ; //without the ~<br>
//Converts all HTML spaces back to white spaces for MySQL to understand.<br>
//Useful when you load data onto textboxes:<br>
//Let's say you have a surname Van Der Merwe with white spaces.<br>
//To edit the surname we need to put it into an input textbox:<br>
$DBConnect = new mysqli("localhost", "root","Userpassword", "DBName");<br>
For associative array:
if ($result = mysqli_query($DBConnect, $query)) {<br>
while ($row = mysqli_fetch_assoc($result)) {<br><br>
echo "<>input type='text' name='Surname' size='45' value=";<br>
echo <b>strtr</b>($row['Surname'], array(' ' => '&nbs#p;')) ;//remove the # "<br>
echo ">";<br><br>
For non-associative array:
if ($result = $DBConnect->query($SQLstring)) {<br>
while ($row = $result->fetch_row()) {<br>
echo "<dd><>input type='text' name='Surname' size='45' value=";<br>
echo <b>strtr</b>($row[2], array(' ' => ' #;')) ; //remove the #<br>
echo ">";<br>
I've got a database table with at least three rows in it. From php, I have successfully connected to my db and extracted all table information with 'SELECT * from mytable' .
Now I want to loop through first each row, and then each cell, printing out the contents of each cell.
I know this might be a simple task for a more experienced programmer, but I can't figure it out, and I can't find any examples online and it's driving me stark raving bonkers.
How can I do this ?
You could use a for each loop...
//Do the query
$query = "SELECT * FROM table";
$result = mysql_query($query);
//iterate over all the rows
while($row = mysql_fetch_assoc($result)){
//iterate over all the fields
foreach($row as $key => $val){
//generate output
echo $key . ": " . $val . "<BR />";
}
}
Haven't tested it, so there may be a syntax error in it, but this is the main idea
There are a couple of examples in the manual that could help you with that ; for instance, on the manual page of mysql_query (quoting, and adapting a bit) :
You first have to execute the query :
$result = mysql_query('SELECT * from mytable');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Note that dying in case of an error, and echoing the error-message, is OK while developping -- but you shouldn't do that in a production environment !
And, then, you have to loop over the lines of results, fetching them one at a time :
while ($row = mysql_fetch_assoc($result)) {
// Use the data in $row
}
And, inside this loop, as $row is an array, you can iterate over its content with a foreach loop :
foreach ($row as $name => $value) {
echo "column $name contains $value<br />";
}
Note : at this point, you should really invest some time going through a couple of sections of the PHP manual : it will take some time, yes ; but it will definitely help you, and will not be wasted time :-)