This question already has answers here:
PHP Insert data from one table to another
(2 answers)
Closed 3 years ago.
I have a simple query that is returning some results from my database, it returns 4 rows, but when I do the insert it's only doing the first row and then stopping, does not seem to be doing an insert for each row that is returned from the first query.
$sql = "SELECT t.ID AS 'TopicID', t.seminar_id AS 'SeminarID', rl.resourceid AS 'ResourceID', r.ResourceType AS 'ResourceType'
FROM topic t
LEFT JOIN resourcelink rl ON rl.entityid = t.ID
LEFT JOIN resources r ON r.ResourceID = rl.resourceid
WHERE t.seminar_id = '124840'";
$result = mysql_query($sql);
// echo "<pre>";
// print_r($sql);
// echo "</pre>";
while($row = mysql_fetch_assoc($result))
{
$resourceID = $row['ResourceID'];
$resourceType = $row['ResourceType'];
if ($resourceID != '' && $resourceType != 1)
{
$sql_insert = "INSERT INTO resourcelink (resourceid, entityid, entitytype, linkorder, viewinplayer)
VALUES ($resourceID, $topicID, 1, 0, 0)";
$result = mysql_query($sql_insert);
}
}
The reason is that you're overwriting the $result variable when you do the first insert. So when the next iteration of the while loop calls mysql_fetch_assoc($result), it's fetching the result of the INSERT, not the result of the SELECT.
Since you never do anything with the result of the INSERT, there's no need to assign a variable. If you do need to use the result, you should use a different variable name. So change:
$result = mysql_query($sql_insert);
to
mysql_query($sql_insert) or die("Insert error: " . mysql_error());
Related
This question already has answers here:
How to get count of rows in MySQL table using PHP?
(3 answers)
Closed 2 years ago.
How do I display this query result:
from MySQL onto a webpage, just like this:
?
I want to display the count only. I did run the same query through PHP but its returning '2'. The PHP code is below
<?php
//Connection for database
$conn = mysqli_connect("localhost", "root", "aaaaa", "db");
$query = "SELECT `gender`,COUNT(`gender`) FROM `reg` GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result)
{
// it return number of rows in the table.
$row = mysqli_num_rows($result);
if ($row)
{
printf("" . $row);
}
// close the result.
mysqli_free_result($result);
}
// Connection close
mysqli_close($conn);
?>
Please note that I have gone through other answers like this one but I can't really find my way through, I want the value count only not the total number of all rows in the table, .e.g. count for 'Male'.
You're using mysqli_num_rows(), which returns the number of rows in the result, not the actual data in the result. For that you need to use mysqli_fetch_assoc().
Your could would become:
$query = "SELECT `gender`,
COUNT(`gender`) AS `count`
FROM `reg`
GROUP BY `gender`";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$gender = $row['gender'];
$count = $row['count'];
echo "$gender = $count<br>";
}
mysqli_free_result($result);
}
Note that I slightly changed your query to make the count accessible.
This question already has answers here:
How to solve PHP error 'Notice: Array to string conversion in...'
(6 answers)
Create PHP array from MySQL column
(12 answers)
Closed 2 years ago.
When I ran the following query in PHPMyAdmin, it returned the correct number of results. However when I try to echo the results in PHP, it only outputs one result, even when there is more thn one. How do I fix this so that every result is displayed?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
while ($row1 = mysqli_fetch_assoc($result1)) {
$names = $row1['userFirstname'];
}
}
echo($names);
Second attempt: I tried creating an array. But this just outputs the word array and the error message, "Notice: Array to string conversion". Why?
$sql1 = "SELECT userFirstname FROM users WHERE userID IN (SELECT userID FROM note_editors WHERE noteID = (SELECT noteID FROM notes WHERE uniqueID = ?))";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header("Location: note-premium.php?error=sql");
exit();
}
else {
mysqli_stmt_bind_param($stmt1, "s", $unique);
mysqli_stmt_execute($stmt1);
$result1 = mysqli_stmt_get_result($stmt1);
$column = array();
while ($row1 = mysqli_fetch_assoc($result1)) {
$column[] = $row1['userFirstname'];
}
}
echo($column);
As you're looping through the results and storing the value of the column 'userFirstName' in $names, you're overwriting the previous value stored in it.
You've got two options - display the value as you're looping through the results, or store the value in an array and then display that afterwards.
Option 1 - display the value as you're looping through the results:
while ($row1 = mysqli_fetch_assoc($result1)) {
echo $row1['userFirstname'];
}
Option 2 - store the values in an array and display that after the loop
$names = [];
while ($row1 = mysqli_fetch_assoc($result1)) {
$names[] = $row1['userFirstname'];
}
foreach($names as $name) {
echo '<p>'.$name.'</p>';
}
Obviously you can customise how you want to loop through the array values and display them. I've wrapped each value in a <p> tag so that they display on a new line. If you just want to display the unformatted contents of the array, use print_r($names)
This question already has answers here:
Create array in PHP from mysql
(2 answers)
php update to mysql with array not updating
(3 answers)
Closed 4 years ago.
I'm trying to use the results of a MySQL select in a php script and make some updates in the same table.
For the following query, I need to look at each record and say "if order_status = 'S', set is_placement to 1 (this is a bit) and set date_updated to curdate()"
I can do that with an update, but the trick is I need to store the order_id of those with the status of 'S' in an array to use in another query.
I'm not sure how I would loop and store those in an array for that.
Here's the select:
$orderCheck = "
SELECT
order_id,
order_status
FROM order_status
";
EDIT (based on answers below): So I can make an array of order IDs like so:
$result = mysqli_query($connection,$orderCheck);
while ($row = mysqli_fetch_array($result))
{
$array = $row['order_id'}
if($row['order_status'] == 'S'){
Store ORder IDs here
}
}
But with that array and stored order IDs, I need to update the records for each ID.
How can I preform that update and store the necessary IDs as well?
The following will store the data the way you needed:
$result = mysql_query($orderCheck);
$order_ids = array();
while ($row = mysql_fetch_array($result))
{
$order_id = $row['order_id'];
if ($row['order_status'] == "S")
{
array_push($order_ids, $order_id);
}
}
$orderCheck = "SELECT
order_id,order_status FROM jfi_sales.order_status ";
$result = mysql_query($orderCheck );
$ids= array();
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
if($row['order_status'] == 'S'){
$ids[]= $row['order_id'];
}
}
print_r($ids);
Now $ids is your array of order id whose order status is 'S'.Try this it will work.
This question already has answers here:
why this mysql query is not working?
(7 answers)
Closed 8 years ago.
Please help me regarding the specified problem:
The code section:
$result = mysql_query("SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate,
UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where
id='$_GET[id]' ORDER BY eventdate");
// the above query is not working
if (! $result) {
echo mysql_errno() . ": " . mysql_error(). "\n";
}
if ( mysql_num_rows($result) == 0 ) {
print "<p>No events right now.</p>\n";
}
else {
$lasteventmonth = '';
while ($row = mysql_fetch_array($result)) {
$eventmonth="";
$eventmonth = date("F Y",$row['eventdate']);
if ($lasteventmonth != $eventmonth) {
print "<p style='font-size: 18px;'><b>$eventmonth</b></p>";
}
$lasteventmonth = $eventmonth;
showEvent($row);
}
}
?>
........................
........................//other codes
when the code evaluates as follows:
No events right now.
But specific id is present in the database and if $_GET['id'] is echoed in the page the value is shown.
what is id in id='$_GET[id]' at the beginning?
If you have a query http:// ... ?id=123, I would put id in quotes. Having said that, better like this:
$id = mysql_real_escape_string($_GET['id']); // safe against SQL injection
$sql = "SELECT *, UNIX_TIMESTAMP(eventdate) AS eventdate, UNIX_TIMESTAMP(throughdate) AS throughdate FROM events where id='$id' ORDER BY eventdate";
$result = mysql_query($sql);
If you are still getting trouble, use echo to check the variables $id and $result before the query runs; then you will have a clearer idea why it is not running the query you expect.
I am sure id=$_GET[id] is checking an int versus an int where you have it checking an int vs a string. Remove the single quotes around $_GET['id'] and try again. The single quotes define it as a string rather than an int.
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 6 months ago.
I want to select only unique values with php/mysql.
I can do it with many line, but I forget how to do it without while... :)
Thanks a lot.
Here is the code that I want to do without while.
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
while($row = mysql_fetch_array($result_1m))
{
/* Get the data from the query result */
$date1_1m = $row["date1"];
$date2_1m = $row["date2"];
}
mysql_fetch_assoc + SELECT with DISTINCT
I'm not sure I understand your question, but here's what I think you want to do :
$request_1m = "SELECT date1, date2 from mytable";
$result_1m = mysql_query($request_1m,$db);
list($date1_1m, $date2_1m) = mysql_fetch_row($result_1m);
Note that this will only get the first row from the result set (just as if you LIMIT 1)
like this?
$dbresult = mysql_query("SELECT DISTINCT field FROM table");
$result = array();
while ($row = mysql_fetch_assoc($dbresult))
{
$result[] = $row;
}
This gets you all unique values from "field" in table "table".
If you really wish to avoid the while loop, you can use the PHP PDO objects, and in particular call the PDO fetchAll() method to retrieve the complete results array in one go. PDO fetchAll() documentation
$db = new PDO('dblib:host=your_hostname;otherparams...');
$db->query("SELECT DISTINCT col FROM table");
$results = $db->fetchAll();
// All your result rows are now in $results
Heres how I do it and Json encode after. This will ensure it will encode only UNIQUE json Values (Without duplicates) as an example
$tbl_nm = "POS_P";
$prod_cat = "prod_cat";
//Select from the POS_P Table the Unique Product Categories using the DISTINCT syntax
$sql = "SELECT DISTINCT $prod_cat FROM $tbl_nm";
//Store the SQL query into the products variable below.
$products = mysql_query($sql);
if ($products){
// Create an array
$rows = array();
// Fetch and populate array
while($row = mysql_fetch_assoc($products)) {
$rows[]=$row;
}
// Convert array to json format
$json = json_encode(array('Categories'=>$rows));
echo $json;
}
//Close db connection when done
mysql_close($con);
?>
That is very easy, take out the while, like below
$row = mysqli_fetch_assoc($result);
$date1_1m = $row["date1"];