I have a MySQL table that looks like this
index (auto incremented)
data
type
1
a1
1
3
a2
1
4
b62
3
9
m52
1
and i loop through it with this code
for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}
but as you can see that it would fail cause the auto incremented indexes are not sequential.so at i=2 it would fail without making it to i=3.
any idea how to make it select the next index in the table
Simple solution
Don't use * use specified column names
Use one query to retrieve the entire result set
Use OOP approach and save yourself having to repeat code (you don't neeed to change the connection but you can:
// From...
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// To...
$db = new mysqli($db_host,$db_user,$db_pass,$db_name)
I assume that type is an integer field; no need to use quotation marks in the query
Code
// Run the query to select the messages
$sql = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query = $db->query($sql);
// Option 1
// Loop though result set with a foreach loop
foreach ($query as $message) {
echo $message[0];
}
// Option 2
// Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
echo $message["data"];
}
Related
This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}
On my XAMPP server I have a database table on phpMyAdmin. In that table, I have a few columns, and one of them is id column (Integer).
I want to get the latest added item's ID, increment it by one and then assign it to a new item that the function adds to the table.
The problem is that whenever there is a new item, it is automatically assigned with 1 as id, nothing above 1.
$sql = "SELECT * FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
if( $_SESSION["increment"] == "yes"){
$_SESSION["id"] = $row["id"];
}else
$_SESSION["id"]=$_SESSION["id"]+1;
}
} else {
$_SESSION["id"] = 1;
}
This will give you last increment Id.
$sql = "SELECT id FROM items order by id DESC LIMIT 0,1";
Then you dont want have a while loop to find last increment Id.
error reporting said what? and mysqli_error($conn)?
-- Fred-ii-
The above request by Fred -ii- sums it up, if your ->num_rows is returning zero or not a number (false) then you have an SQL error, so you need to check your error logs, and check your database connection.
Have you started your session with session_start?
Do you intend that the first else calls without brackets, only executing the single following line, $_SESSION["id"]=$_SESSION["id"]+1; ?
It seems to me that you need well known AUTO_INCREMENT functionality built inside MySQL database. Just define in your database schema for your table that column is AUTO_INCREMENT column type, and it will be automatically incremented by 1 upon each new insert into table.
I did search for answer before I posted :) !
Now my problem is php mysql script have to count records in mysql database cells I will try to draw my db now
table name: tableurl (table contains two columns url and clicks)
----------------
url clicks
clhgfghfh 6
hgjhgjhgh 0
kjhgjhgjh 0
khgjhgjhg 1
asdasddsg 5
-----------------
Now I want to count all the clicks so output should be 12 ! here is my code
<?php
/* db connection included in head*/
$sql ="SELECT count(clicks) FROM tableurl";
if ($result=mysqli_query($con,$sql))
{
$rowcount=mysqli_num_rows($result);
printf("Clicks together %d \n",$rowcount);
mysqli_free_result($result);
}
?>
P.S. clicks in db is defined as INT
lenght/value is 1
default is NULL
Any input what I'm doing wrong ?
You want to sum the clicks and not count the number of records in your table. Use SUM()
SELECT sum(clicks) as click_sum
FROM tableurl
and then use something like
if($row = $result->fetch_assoc()) {
$sum = $row["click_sum"];
...
}
Try with -
$sql ="SELECT SUM(clicks) as totalClicks FROM tableurl";
if ($result=mysqli_query($con,$sql))
{
$res = mysqli_fetch_array($result);
printf("Clicks together %d \n",$res['totalClicks']);
mysqli_free_result($result);
}
I am trying to run an update on a MySQL table that will swap the contents of 1 field with the contents of another (both in the same table).
Here is the basic structure of the table:
id SKU related
== === =======
1234 SKU001 1234,8889,2209
5544 SKU855 2209,1234
2209 SKUYYT 5544
What I need to do is swap the related field for the relavent SKU (so that it lists the sku's instead of the id's). So it would end up looking like this:
id SKU related
== === =======
1234 SKU001 SKU001,SKU111,SKUYYT
5544 SKU855 SKUYYT,SKU001
2209 SKUYYT SKU855
So what I'm trying to achieve is the id in the related field would have been replaced with the SKU that relates to that id.
What I'm currently doing is this:
SELECT id, sku FROM my_table
Then looping through all id's with PHP and updating the table like so:
UPDATE my_table SET related = REPLACE(related, '5544', 'SKU855');
This seems to work but I have 9000+ rows and multiple id's in the related column and it's taking hours to complete
Can anyone suggest a better way of achieving this? (Ideally in MySQL)
Many thanks
If you have access to PHP with this update, I would suggest you do the following:
$rows = some_method_to_load_all_rows_from_your_table();
$id_to_sku = array();
// Loop through all rows to cache their SKU numbers and directly associate them to their row's PK.
foreach ($rows as $row) {
$id_to_sku[$row['id']] = $row['SKU'];
}
// Loop through all rows a second time to then break apart, find, and replace the related IDs.
foreach ($rows as $index => $row) {
$related_ids = explode(',', $row['related']);
foreach($related_ids as &$related_id) {
if (isset($id_to_sku[$related_id]]) {
$related_id = $id_to_sku[$related_id]];
} // else the ID couldn't be found.
}
$rows[$index]['related'] = implode(',', $related_ids);
}
// $rows now contains the related string with the SKU numbers instead of ID numbers.
method_to_update_all_rows_with_new_related_value($rows);
Essentially, doing this in raw SQL is going to be very difficult, and you will be left with a very complex query. The best way is to abstract the detecting and replacing of the IDs / SKU numbers into PHP, where this becomes a much easier and more readable platform to work on.
The code loads all rows in the table, then loops through each row to cache it’s ID and SKU number separately.
Then, we loop through each row again, break apart the related field into an array of IDs, replace those IDs with their correct SKU code using the cache we created, and insert them back into $rows.
$rows becomes the new updated table set. From there, it’s a case of creating a giant UPDATE statement, or looping through each row and executing a single UPDATE statement for each one. Looping in PHP and issuing an UPDATE for each row would be slower as making a query has overhead. But you can also implement the loop in SQL, using stored procedure, avoiding the overhead on communication between your application and database.
/*
create my_table_temp with same structure as in my_table
*/
$mapping = array();
$sth = $dbh->prepare("SELECT id, SKU FROM my_table");
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
$mapping[$row['id']] = $row['SKU'];
}
$sql = 'insert into my_table_temp(id, SKU, related) VALUES ';
$params = array();
$sth = $dbh->prepare("SELECT * FROM my_table");
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) {
$related = explode(',', $row['related']);
foreach($related as &$val) {
$val = $mapping[$val];
}
$sql .= '(?, ?, ?),';
$params[] = $row['id'];
$params[] = $row['SKU'];
$params[] = implode(',', $related);
}
$sql = rtrim($sql, ',');
$sth = $dbh->prepare($sql);
$sth->execute($params);
/*
update my_table
set related = q.related
from (
select sku, related
from my_table_temp
) q
where my_table.sku = q.sku;
drop table my_table_temp;
*/
When You are asking to do it in mysql , then it would be possible by using CURSOR and dynamic query.
DELIMITER //
CREATE PROCEDURE `all_update`()
BEGIN
DECLARE ids INT;
DECLARE sname VARCHAR(255);
DECLARE finished INTEGER DEFAULT 0;
DECLARE cursor1 CURSOR FOR SELECT id,SKU FROM testing;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN cursor1;
update_table: LOOP
FETCH cursor1 INTO ids,sname;
IF finished = 1 THEN
LEAVE update_table;
END IF;
SET #s = CONCAT('UPDATE testing SET related = REPLACE(related,', ids,', "',sname,'")');
PREPARE stmt1 FROM #s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END LOOP update_table;
CLOSE cursor1;
END//
Fiddle is http://sqlfiddle.com/#!2/298a7/1
I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}