I'm trying to assign a field called 'uniqueid' to each row present in my database. There are roughly 188,000 rows available.
Here is the code I am using:
$connection = mysql_connect("localhost","root","root");
mysql_select_db("comics",$connection) or die ("Database not found");
$query = mysql_query("select * from comic_issues");
if ($query){
$rows = mysql_num_rows($query);
foreach($rows as $row){
$str = strtolower($row['series'].$row['volume'].$row['issue']);
$str = preg_replace('/[^A-Za-z0-9]/', '', $str);
$update = "update comic_issues set uniqueid='" . $str . "' where id='" . $row['ID'] . "'";
mysql_query($update);
exit();
}
}
What is happening is that every row gets updated with the same uniqueid, which seems to be a different value each time I run the script.
Instead of
foreach($rows as $row){
you need to do
while ($row = mysql_fetch_row($query)) {
In your code $rows is a number and not an array, therefore you can't do a foreach on it.
Just let MySQL do it all for you:
UPDATE comic_issues SET uniqueid = LOWER(CONCAT(series,volume,issue))
If you must also strip all non-alphanumeric characters, you can either write a stored function or else use a UDF.
Related
When I fetch items from a database using php and mysql, I usually just push each row into an array:
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
mysqli_set_charset($db, 'utf8'); //important! or it won't echo the array
$data = array();
$q = "SELECT distinct(procedure_codes), procedure_name FROM `hospital_transparency_data` order by procedure_codes";
$result = $db->query($q);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row; //whole row goes in
}
$db->close();
echo json_encode($data);
But in this case, I want to push each item in the $row into the array individually because I want to add a dollar sign to one of the row items. I still want the name of the field associated with its value, I guess kind of like "full_payer_name"-->$row["full_payer_name"]. How would I do that?
$datastring = $_POST['datastring'];
$q = "SELECT procedure_name, procedure_codes, hospital_name, raw_description, full_payer_name, plan_type, price FROM `hospital_transparency_data` where " . $datastring . " order by procedure_name, hospital_name, full_payer_name";
$result = $db->query($q);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//Add this row to the reply
array_push($data, $row["procedure_name"], $row["procedure_codes"], $row["hospital_name"], $row["raw_description"], $row["full_payer_name"], $row["plan_type"], "$" . $row["price"]);
//works, but doesn't have the field name associated with the value
}
Just add the $ to the row element before pushing onto the array.
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row['price'] = '$' . $row['price'];
$data[] = $row; //whole row goes in
}
You can add it as part of the SQL, this means you don't need to do anything special with the result set. Use CONCAT('$', price) to add it...
$q = "SELECT procedure_name, procedure_codes, hospital_name,
raw_description, full_payer_name, plan_type,
CONCAT('$', price) as price
FROM `hospital_transparency_data`
where " . $datastring . "
order by procedure_name, hospital_name, full_payer_name";
You may also be able to use fetch_all which stops you having to loop over each row to add it in.
Alright, so I have a database, each with an ID, a name and a textvalue.
I wish to be able to print each of a specific row individually. When I use
$result = mysql_query("SELECT * FROM mytable", $db);
$row = mysql_fetch_array($result);
echo $row['text'];
I am only able to print the first row, as it doesn't select any specifics. The problem is, I'm not sure how to use the WHERE ID='X', as I want the first one to print the first column, the second to print the second column and so forth (there are a total of 13 lines). I want to echo them on different places on the page, so just calling everything at once is not what I'm looking for.
The way things are now, I'll have to use the code above for each time I want to print it, and manually edit the WHERE ID='1' on the first print, the second to WHERE ID='2' and so on, which is rather a pain in the ass.
Any suggestions is appreciated.
Keep calling mysql_fetch_array until it returns null:
while($row = mysql_fetch_array($result ))
{
echo $row['text'] . '<br/>';
}
This is shown in the documentation, which also will tell you this:
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. 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:
Here's an example using a more object-oriented approach:
1) setup a PDO object like this:
$dbhost = '127.0.0.1';
$dbuser = 'yourDbUsername';
$dbpass = 'yourDbPassword';
$dbname = 'databaseName';
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$dbAdapter = new PDO($dsn,$dbuser,$dbpass);
$dbAdapter->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbAdapter->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
2) use PDO objects to run queries and fetch result sets:
$sql = 'SELECT * FROM mytable';
$statementObject = $dbAdapter->query($sql);
$resultSet = $statementObject->fetchAll();
3) iterate over the resulting array:
foreach($resultSet as $row){
echo $row['text'] . "<br />";
}
This is how to iterate through all records.
$result = mysql_query("SELECT text FROM mytable", $db);
while ( $row = mysql_fetch_array($result) ) {
echo $row['text'];
}
$i = 1;
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $i . ' - ' . $row[0] . '<br/>';
$i++
}
If you want 4 variables with the text to use in differents part of your code then use:
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
$var1 = mysql_fetch_array($result, MYSQL_NUM);
echo $var1[0];
$var2 = mysql_fetch_array($result, MYSQL_NUM);
echo $var2[0];
$var3 = mysql_fetch_array($result, MYSQL_NUM);
echo $var3[0];
$var4 = mysql_fetch_array($result, MYSQL_NUM);
echo $var4[0];
I'm attempting to utilize 2 mysql tables via php/mysql 2 get me a max value. I'm assuming using an array is the correct way to do this, but I've been spending many hours and am missing something.
My tables are:
1) plantcomp, where I want to know all the CompressID listings that have a CustID of $CustID. (there are currently 3).
2) comps, where I want to use those CompressID listings to know the valid Compressor #s. I'll then do a max() on those values so I can name the next compressor max()+1.
My code attempts...This gets me an error: "Notice: Array to string conversion in (pathname) on line 55", then "Array"
//have the custid
echo $CustID;
//under table `plantcomp`, find matching compressid's.
$q55 = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
// Run query
$result55 = mysql_query($q55);
while($row = mysql_fetch_array($result55)){
echo "<p>".$row;
I also tried this, mysql_fetch_assoc, but it only gives me 2 of my 3 valid entries...
$get = mysql_query("SELECT CompressID FROM plantcomp WHERE CustID = '$CustID'");
$money = mysql_fetch_assoc($get);
while($money = mysql_fetch_assoc($get)){echo $money['CompressID'];}
Thank you in advance for your assistance!!
Please change this line
echo "<p>".$row;
to
echo "<p>";
print_r($row);
The problem you have comes from the fact that you are mixing a string (<p>) with an array ($row).
echo "<p>".$row;
You can print the $row array by using print_r:
print_r($row);
You can also access different elements of the $row array (table columns) like this:
$row['column_name'];
For example, lets say your table consists of two columns: first_name and last_name. You can print them like this:
echo '<p>' . $row['first_name'] . ' ' . $row['last_name'] . '</p>';
So, with that knowledge, we can print your CompressIDs:
$result55 = mysql_query("SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "'");
while ($row = mysql_fetch_assoc($result55))
{
echo '<p>' . $row['CompressID'] . '</p>';
}
$CompressID = array(); //Initialising an array
$query = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
$result = mysql_query($query);
while($obj = mysql_fetch_assoc($result)){
$CompressID = $obj['CompressID']; //Storing all the CompressID in an array
echo $obj['CompressID']; // sanity check
}
First run the above query and compare result with db.If the result is not matching
1)There is some wrong data in db
2)Alter your query to get desired result.
If this is working then add rest of the code
if( count($CompressID) >0 ){
$query = "SELECT max(CompressID) as maxCompressID FROM `comps` WHERE `CompressID` IN($CompressID)";
$result = mysql_query($query);
while($newObj = mysql_fetch_assoc($result){
echo $newObj['maxCompressID'];
}
}
I know this may sound like a stupid question from a programming-newbie, but I just want to make sure I understand correctly.
After a query, what does $row[0] stand for/ result in?
Is my understanding correct that $row[0] shows ALL results?
HERE ARE EXAMPLES:
$query = "SELECT count(commentid) from comments where jokeid = $jokeid";
$result = mysql_query($query);
$row=mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "No comments posted yet. \n";
} else
{
echo $row[0] . "\n";
echo " comments posted. \n";
AND THIS ONE
$query = "Select count(prodid) from products where catid = $catid";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row[0] == 0)
{
echo "<h2><br>Sorry, there are no products in this category</h2>\n";
}
else
{
$totrecords = $row[0];
Thanks in advance.
$row[0] will simply echo the first column in your database.
0 is the first because all arrays in PHP (and in most programming languages) are zero-based - they simply start with zero.
$row[0] will be the value of the first column in your results. If you use mysql_fetch_assoc($result) you will have an array in the form:
array(column_name => column_value);
e.g.
$row = mysql_fetch_asssoc($result);
$value_column_1 = $row['column_1'];
You can also use mysql_fetch_object($result) to get an object with column names as the parameters.
$row = mysql_fetch_object($result);
$value = $row->column_name
mysql_fetch_array() takes the next (in your examples first) row out of the resultset and stores the data in an array $row.
$row[0] now represents the first value of that row.
So in total in your examples the variable holds the first value of the first row of your resultset.
I have a query which is designed to retireve the "name" field for all records in my "tiles" table but when I use print_r on the result all I get is the first record in the database. Below is the code that I have used.
$query = mysql_query("SELECT name FROM tiles");
$tiles = mysql_fetch_array($query);
I really cant see what I have done wrong, I have also tried multiple searches within google but I cant find anything useful on the matter at hand.
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "<br />";
}
?>
'mysql_fetch_array'
Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
This means that it returns array (contains values of each field) of A ROW (a record).
If you want other row, you call it again.
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
// Do something with $row
}
Hope this helps. :D
Use "mysql_fetch_assoc" instead of "mysql_fetch_array".
$query = mysql_query('SELECT * FROM example');
while($row = mysql_fetch_assoc($query)) :
echo $row['whatever'] . "<br />";
endwhile;
I believe you need to do a loop to invoke fetch array until it has retrieved all the rows.
while ($row = mysql_fetch_array($query) ) {
print_r( $row );
}