I'm trying to make a quick lil' script to just add some dummy data to a new column I added to a database table I have, the table has 1000 entries so doing it by hand isn't really an option.
What I have right now it:
<?php
$conn = mysql_connect('localhost', 'root', ''); mysql_select_db('cdb', $conn);
$string = "4050605040302030405060708070304050403040506070605040302010203040506070655545352515756535243515353545"; //50 values
$mpgsplit = str_split($string, 2);
for ($i=0; $i<=20; $i++)
{
for ($x=0; $x<=50; $x++)
{$r = mysql_query ("UPDATE cars SET mpg = '".$mpgsplit[$x]."'", $conn);}
}
?>
Issue being using update doesn't work as it just replaces the value of every row of that column with each number every time it loops. For me it reached number 48 in the array and timed out.
Then using insert just makes all new rows.
So I need a way to cycle through each row and update it.
The nearest I've been to looping through and dealing with singular rows of a table is this:
$result = mysql_query("SELECT * FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
$file = fopen('Order.txt', 'w');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
But thats just taking the row as a variable, not sure if I can translate that to what I need.
Theres probably a simple function out there which does this, but I've tried searching and can't find it. Theres also probably an easier way to achieve what I'm trying to do overall as well, so that would be welcome.
All help much appreciated. -Tom
Issue this sql statement directly in mysql command line or from a php script.
SET #r := 0;
UPDATE cars
SET mpg = (#r := #r + 1)
ORDER BY
RAND()
This sql statement will assign number from 0 till Total row count of your db to a random row. I guess it might be helpful
Related
I am using php and mysql to create a page that displays all of the jobs we have in the database. The data is shown is a table and when a row is clicked a modal window triggers with the information of the clicked job inside. At the top of the page I want a simple counter that shows amount of paid jobs, invoiced jobs etc etc. I am using the code below but having no luck...
<?php
$con = mysql_connect("localhost","databaseusername","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$result = mysql_query("select count(1) FROM jobslist");
$row = mysql_fetch_array($result);
$total = $row[0];
mysql_close($con);
?>
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0. No matter what I try I can't seem to get it to count the amount of 'paid' items in the database or 'invoiced' etc etc.
Once the count function is complete currently I am echoing out the outcome as below:
<?php echo "" . $total;?>
I am sure I am overlooking something simple, but any help is appreciated.
EDIT: TABLE STRUCTURE INCLUDED
http://i.stack.imgur.com/hcMJV.png
Assuming a column called paid you could restructure the query similar to the following. If you needed to sum the amounts involved that requires additional tweaking.
$result = mysql_query("select
( select count(*) from `jobslist` where `paid`=1 ) as 'paid',
( select count(*) from `jobslist` where `paid`=0 ) as 'unpaid'
from jobslist");
$rows = mysql_num_rows( $result );
while( $rs=mysql_fetch_object( $result ) ){
$paid=$rs->paid;
$unpaid=$rs->unpaid;
echo 'Total: '.$rows.'Paid: '. $paid.' Unpaid: '.$unpaid;
}
When I do this I usually name the COUNT result. Try this out:
$result = mysql_query("SELECT COUNT(*) AS total_rows FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['total_rows'];
If you do not want to name the COUNT result, then give the following a go:
$result = mysql_query("SELECT COUNT(*) FROM jobslist;");
$row = mysql_fetch_array($result);
$total = $row['COUNT(*)'];
select count(1) FROM jobslist
This code as far as I am aware is counting the amount of INT columns set to 1 rather than 0.
No, this is just counting rows in your table and not filtering. If you want to count something with a specific filter you have to add that filter condition:
SELECT COUNT(*) AS `MyCount`
FROM `joblist`
WHERE `MyColumn` = 1; -- assuming MyColumn contains the INT you're looking for
You should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
First you should change deprecated mysql_... to mysqli_... (look here how to). But it's not the reason you fail.
Unlike you seem to suppose, COUNT(1) will not look for an INT column having value 1.
Instead you must use COUNT(*) or COUNT(a_column_name) (same result), with adding a WHERE clause stating which condition is involved.
Here you seem wanting to count records where a given column (say the_column) has value 1. So you should:
SELECT COUNT(*)
FROM jobslist
WHERE the_column = 1
Last point: you don't need echo "" . in <?php echo "" . $total;?>.
Merely write <?php echo $total;?>.
I would like to get the count of the mysql query results in php.
The query usually returns up to 10 rows.
Which one in the below is better to use:
1.
$query = "SELECT * FROM test_table WHERE test_no=12345";
$queryResult = $db->query($query);
$count = $queryResult->size();
if($count < 5){}
2.
$query = "SELECT COUNT(test) AS count FROM test_table WHERE test_no=12345";
$queryResult = $db->query($query);
$result = $queryResult->fetch();
if($result['count'] < 5){}
Also, please let me know if there is another better way to use it
$query = 'SELECT COUNT(1) FROM test_table WHERE test_no=12345';
$queryResult = $db->query($query);
$count = $queryResult->fetchColumn();
This is the best way, assuming you are using PDO. Do not specify a column name in COUNT(), use * or 1. Then use fetchColumn() to get the first column's data.
It's probably better to let MySQL handle row counting. This is more important when large amounts of data are in play. If PHP were in charge of counting the rows, all of that data would need to be sent from MySQL to PHP, only for PHP to then count & discard it. It's better to skip the middle man. So the SELECT COUNT(test) query is the preferable one, of the two choices you provided.
If you're using PDO, the best way is to use PDO's rowCount() method. This methods returns the number of rows returned by the query.
Here's an example.
try
{
$s = $conn->execute("YOUR QUERY HERE");
$count = $s->rowCount();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Im trying to update a value in a table, using while loop, but i want this value to be like using auto_inc key.
My table: ID / CAR_ID / IMG_KEY / IMAGE
i want to take 12 rows of the same CAR_ID and give the IMG_KEY values from 1-12.
I tried the below loops, but the result is giving the IMG_KEY the value 1
$getImages = mysql_query("SELECT * FROM more_images WHERE car_id = '$car_id'") or die(mysql_error());
$img_key = 0;
for ($img_key = 1; $img_key <= mysql_num_rows($getImages); $img_key ++) {
while ($selectedImages = mysql_fetch_assoc($getImages)) {
$update = mysql_query("UPDATE `more_images` SET `img_key` = '$img_key' WHERE `car_id` = '$car_id'") or die(mysql_error());
}
}
The goal is give to the following 12 rows img_key values from 1 to 12 and all the other values as they are.
Ok, I'm still not 100% sure what you want, but my guess is that you are looking for something like this:
$imgKey = 0;
while ($selectedImages = mysql_fetch_assoc($getImages))
{
$imgKey++;
$update = mysql_query("UPDATE `more_images` SET `img_key` = '{$imgKey}' WHERE `car_id` = '{$car_id}'") or die(mysql_error());
}
In your question, your for loop isn't doing anything other than looping, in your case it iterates twelve times.
Since mysql_fetch_assoc($getImages) is a function that loops through all rows in a set of results. So for each iteration of your for loop, it updates all records to have the same $img_key.
Also, really do refrain from using mysql_* functions, they're deprecated. Read this thread:
Why shouldn't I use mysql_* functions in PHP?
I have written some code to update certain rows of a table with a decreasing sequence of numbers. To select the correct rows I have to JOIN two tables. The last row in the table needs to have a value of 0, the second last -1 and so on. To achieve this I use ORDER BY DESC. Unfortunately my code brings up the following error:
Incorrect usage of UPDATE and ORDER BY
My reading suggests that I can't use UPDATE, JOIN and ORDER BY together. I've read that maybe subqueries might help? I don't really have any idea how to change my code to do this. Perhaps someone could post a modified version that will work?
while($row = mysql_fetch_array( $result )) {
$products_id = $row['products_id'];
$products_stock_attributes = $row['products_stock_attributes'];
mysql_query("SET #i = 0");
$result2 = mysql_query("UPDATE orders_products op, orders ord
SET op.stock_when_purchased = (#i:=(#i - op.products_quantity))
WHERE op.orders_id = ord.orders_id
AND op.products_id = '$products_id'
AND op.products_stock_attributes = '$products_stock_attributes'
AND op.stock_when_purchased < 0
AND ord.orders_status = 2
ORDER BY orders_products_id DESC")
or die(mysql_error());
}
Just remove your ORDER BY in your UPDATE statement, then put it in your SELECT statement.
sample:
$query = "SELECT ........ ORDER BY ..."
$result = mysql_query($query);
while(....){.... }
UPDATE statement wont accept ORDER BY clause.
You could use a SELECT call to loop through the rows, and include your WHERE and ORDER BY statements there, and then within your while($row = mysql_fetch_assoc($query)){ loop you'd have your UPDATE table SET key = 'value' WHERE id = '{$row['id']}' statement.
Sure, this would require executing mysql_query() a lot, but it'll still run pretty fast, just not at the same speed a single query would.
Why do you need an order by in an update. I think you could just remove it and you update will update everything that respect your where statement.
EDIT: And maybe you could call a stored proc to simplify your code
I'm trying to fetch random no. of entries from a database by using
SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10
it returns a column of database.
If I want to save all the entries in a array, then which php function do I have to use to save the column.
Something along the lines of this?
$result = mysql_query("SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10");
$rows = array();
while ($row = mysql_fetch_row($result)) {
$rows[] = $row[0];
}
Updated to not use the $i variable as pointed out in the first post and the comment.
Look at some examples for how to run a query and get a result set.
http://www.php.net/mysqli
Once you have the result in a variable, do this:
$myarray = array();
while($row = mysqli_fetch_row($result))
$myarray[] = $row[0];
With PDO:
$qryStmt = $dbc->query('SELECT QNO FROM TABLE ORDER BY RAND() LIMIT 10');
$a = $qryStmt->fetchAll( PDO::FETCH_COLUMN );
BTW: If you just want to get one row by random, this is much faster esp. for large tables:
select * from table limit 12345,1;
where 12345 is just a random number calculated from the count() of rows.
see here, which is more for rails, but have a look at the comments too.
But be careful: in limit 12345,2 - the second row is not random but just the next row after the random row. And be careful: When I remember right (eg. SQLServer) rand() could be optimized by databases other than mysql resulting in the same random number for all rows which makes the result not random. This is important, when your code should be database agnostic.
a last one: do not mix up "random" with "hard to predict", which is not the same. So the order by example "select top 10 ... order by rand()" on SQLServer results in two different result sets when run twice, BUT: if you look at the 10 records, they lie close to each other in the db, which means, they are not random.