<?php
$db = mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db('my_db', $db) or die(mysql_error($db));
$query = 'SELECT
second, count(*) FROM tb_one GROUP BY second';
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $value) {
$queryy = 'INSERT INTO tb_two (name) VALUES ("' . $value . '")';
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
?>
In this script first query is meant to select and count duplicate values(that works well), But in second query I want to insert the selected data in another table which has two columns, first column for its name and second column for its count of duplicate...If there is one column in the insert statement it works well and adds values. But I want two columns- one for name and one for its counted number of duplicates. thank you sir...I have been trying it for many days..
You can do this all in MySQL:
INSERT INTO tb_two(name, count)
SELECT second, count(*)
FROM tb_one
GROUP BY second;
Though, in other news the mysql_ functions have been deprecated. You should be using the PDO Library. Or at least the MySQL Improved Library.
Make your life easier by aliasing the duplicate column, so you can address it more easily.
Here is how:
Replace this
$query = 'SELECT second, count(*) FROM tb_one GROUP BY second';
by this:
$query = 'SELECT second, count(*) as duplicates FROM tb_one GROUP BY second';
You now have "duplicates" as the column name. Then you can use it, like this for example:
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $r) {
$queryy = "INSERT INTO tb_two SET name='".$r['second']."', duplicates='".$r['duplicates']."'";
mysql_query($queryy, $db) or die(mysql_error($db));
}
}
Try this, sorry if it has a syntax issue, I did it in notepad.
while ($row = mysql_fetch_assoc($result))
{
$query = "INSERT INTO tb_two (column1, column2) VALUES ('" . $row[0] . "', '" . $row[1] . "')";
mysql_query($query, $db) or die(mysql_error($db));
}
Related
$select = "SELECT MAX(order_id) FROM `order`";
mysql_query($select);
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
$result2 = mysql_query($query1);
The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id
$select="SELECT MAX(order_id) FROM `order`";
$row = mysqli_query($con,$select);
if(mysqli_num_rows($row)>0)
{
while($data = mysqli_fetch_assoc($row))
{
$order_id = $data['order_id'];
}
}
//This way you can fetch data
Then use this while inserting value for order_id in your query as in
$query1="INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$order_id','$value22[4]')";
one another way to find last inserted id from the db connection:
mysql_query('INSERT INTO order(a) VALUES('b'));
$id = mysql_insert_id();
then $id will be last inserted id
Recommendation:
Use only one batch INSERT query. It gives you the opportunity to insert multiple rows at once, e.g. by running only one query. And is a lot faster.
Used method:
Extract maximum of order_id from order and assign to $maxOrderId.
Iterate through cookie items and build corresponding rows
part of the INSERT sql statement. Then add it to the array $insertRowValues.
In the end implode the $insertRowValues array into the batch INSERT statement.
Run the batch INSERT query - only once.
<?php
$select = "SELECT MAX(order_id) FROM `order`";
$maxOrderId = mysql_query($select);
$insertRowValues = array();
foreach ($_COOKIE['item'] as $key12 => $value) {
$value22 = explode("__", $value);
$insertRowValues[] = "('', " . $value22[5] . ", '" . $maxOrderId . "', '" . $value22[3] . "', '" . $value22[4] . "')";
}
$query1 = "INSERT INTO `cart`
(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`)
VALUES " . implode(', ', $insertRowValues);
$result2 = mysql_query($query1);
Other recommendations:
Use mysqli or PDO instead of mysql, because mysql is already removed as of PHP 5.5.0 (see MySQL Library - Introduction);
Use exception handling;
Use prepared statements to avoid MySQL injection.
P.S: I couldn't test anything.
Good luck!
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("students");
$id = $_POST['id'];
$grade = $_POST['grade'];
$query = "INSERT INTO `st_table` (`St_id`,`Grade`) VALUES ('$id','$grade')";
$result = mysql_query($query);
$query = "SELECT * from `st_table`";
$result = mysql_query($query);
echo "<table>";
echo "<th>St_id</th><th>Grade</th>";
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['St_id'] . "</td><td>" . $row['Grade'] . "</td></tr>";
}
This code adds values into a table both ID and Grade. I want another query that will be able to count how many As, Bs, Cs, etc. and OUTPUT it on an html table.
Here, Your query is ok just group by Grade not Grades
"SELECT `Grade`, COUNT(*) AS count FROM `st_table` GROUP BY `Grade`";
Here is sqlfiddle
After edit
The query i am mentioning should work for you, you can check fiddle for that as for as you modified code is concerned you have to change your table a bit since you are going to include St_id as well so make it 3 column and correspondingly change query too.
My page displays the name of players of a certain sports team using drop down menus. The coach can log in to pick his team and select the opposition which his team will play against.
When user has selected the team and opposition he clicks submit and the isset function is triggered.
Now I capture the values from the drop down menus and upload it to the correct table in the DB. Everything is pretty straight forward however when I click submit I get the error in the tittle. Any help would be appreciated
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
$opponents_id = $_REQUEST['players'];
var_dump($player_ids);
var_dump($opponents_id);
$query = 'SELECT `name`, `position`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) )
{
$selected[] = $row['name'];
$position[] = $row['position'];
}
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($query))
{
$fixture_id[] = $row['fixture_id'];
}
for ($i=0; sizeof($selected) > $i; $i++){
$sql = mysql_query("INSERT INTO `team` (`selection_id`, `fixture_id`, `player_position`,`player_name`)
VALUES ('$fixture_id[$i]','$position[$i]','$selected[$i]')")
or die(mysql_error());
echo $selected[$i];
echo $position[$i];
echo $fixture_id[$i];
echo'<br>';
}
The Unknown column 'Array' in 'where clause' error means literally what it says -- you tried to put an array value into your where clause.
In this line:
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` = $opponents_id")
or die (mysql_error());
You are using the $opponents_id variable which your var_dump shows is an array containing five values. So, you need to use the IN clause and list them out (just like you did for $player_ids):
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` IN (" . implode(",", $opponents_id) . ");")
or die (mysql_error());
Note: Hopefully you are aware of the tiring subject of the mysql_* family of functions. These are being deprecated and are insecure. I wrote about it a while back: http://www.jorble.com/2012/06/you-are-vulnerable-for-sql-injection/
bodi0 is right, your $opponents_id is an array , if it must be an array so do some things like that
$opponents_id_text=implode(',',$opponents_id);
$query = ("SELECT `fixture_id`
FROM `fixtures`
WHERE `fixture_id` in ($opponents_id_text)")
or die (mysql_error());
The problem is in your second SQL query:
WHERE `fixture_id` = $opponents_id" -
Here the $opponents_id is array (it is converted automatically to array when you assign the value to it from the $_REQUEST, because the HTML component select sends the options as array).
Just implode() it also, like you did for $player_ids.
you did not specified Array properly in sql query.
when we use Arrays we have to specify array number in query
I want to show the maximum value of a particular column of mysql table in php. Here is my code:
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$var = $_POST['value'];
$sql = mysql_query(" SELECT MAX(column) FROM tableName WHERE variable='$var' ") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
echo "Maximum value is :: ".$row['column'];
?>
output:::
Maximum value is ::
Or you could be a bit creative:
$sql = mysql_query("SELECT `column` FROM tableName WHERE variable='$var' ORDER BY `column` DESC LIMIT 1") or die(mysql_error());
This is the same problem that I was searching for a solution. The approach below worked. The solution was using "MYSQLI_NUM". While the code below gives the intended result it still seems way too complex. Is there a way to "short-cut" using the "while" statement to search an array since there is only one returned value?
Selecting a max value only returns one number, yet PHP still seems to require a loop to evaluate an entire array. I was expecting something easy, like: max_value=result(0).
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the database server');
$query = "SELECT MAX(IssueIDNUM) FROM tblIssueList";
$result =$conn->query($query);
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_NUM))
{
$maxresult=$row[0];
echo $maxresult;
}
$result->close();
$conn->close();
?>
With further experimentation, I was also able to adapt the code by Jim H. to develop the following solution. Though it works the code still seems too complex.
// Solution #2
$result =$conn->query("SELECT MAX(IssueIDNUM) `max` FROM tblIssueList");
if (!$result) die($conn->error);
while($row=mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo $row['max'];
}
The real name of column is MAX(column), try:
print_r($row);
You may either do:
$sql = mysql_query(" SELECT MAX(column) AS `column` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Or:
$row = mysql_fetch_row($sql) or die(mysql_error());
echo "Maximum value is :: ".$row[0];
You have two choices. By Index or by Column Name. If you really want to use a column name, alias the column in your query.
$sql = mysql_query(" SELECT MAX(column) `max` FROM tableName WHERE variable='$var' ") or die(mysql_error());
Then you can use
$row['max'];
or
$row[0];
You are probably not returning any rows. You should try WHERE variable LIKE '%$var%';
$sql = mysql_query(" SELECT MAX(column) AS GIVE_A_NAME FROM tableName WHERE variable='$var' ") or die(mysql_error());
and
echo "Maximum value is :: ".$row['GIVE_A_NAME'];
I want to count the number of values in one field in MySQL. I would then like to store the resulting count in the database.
Please help me work out the query required to do this.
Also could you help me to write a count function in PHP?
$query="select count(<column>) as total from <table>";
$result = mysql_query($query);
$total=mysql_result($result,0,"total");
Incomplete question. Fuzzy answering.
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
SELECT COUNT(field) FROM table
http://php.net/manual/en/function.count.php
count($array);
This would return the count of rows in MySQL.
SELECT COUNT(*) AS Column_Count FROM Table_Name
You could also just do this:
SELECT * FROM Table_Name
And count manually via PHP, via:
$query = mysql_query("SELECT * FROM Table_Name");
$count = mysql_num_rows($query);
something like:
function getTotalRows($table,$column = 'id')
{
global $mysql_link;
try
{
$resource = mysql_query(sprintf('SELECT count(%s) AS count FROM %s',$column,$table),$mysql_link);
if($resource !== false)
{
return (int)mysql_result($resource,0,'count');
}
return false;
}catch(Exception $e)
{
return false;
}
}
and them do:
$mysql_link = mysql_connect(....);
$total = getTotalRows('users','id');
To store the result of a count directly in the database, you can use INSERT INTO ... SELECT:
INSERT INTO table1 (count_col) SELECT COUNT(*) FROM table2;
Connect to DB:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
Update column:
$qry = "UPDATE `<my_table>` SET `<column>` = (SELECT COUNT(<column>) FROM <table> )";
Mysql_query($qry);
How to select value are in others posts.