user17422
user17422

Reputation: 383

inserting values into a column using loop in mysql

I have a single column named Roll No in a table named Student I want to insert values from 100 to 450 in that column and I want to do it without manually inserting all the values from 100 to 450. Is there any way I could do it using a loop ? Thanks

Upvotes: 1

Views: 12521

Answers (2)

James Vansteenkiste
James Vansteenkiste

Reputation: 148

Assuming you don't wish to use any other languages, you are going to have to create a MYSQL procedure to accomplish this.

delimiter //

CREATE PROCEDURE insertproc()
BEGIN
    DECLARE i int DEFAULT 100;
    WHILE i <= 450 DO
        INSERT INTO students (rollNo) VALUES (i);
        SET i = i + 1;
    END WHILE;
END//

delimiter ;

Relevant SQLFiddle: http://sqlfiddle.com/#!2/a1320/2

See this similar question which I used as my source: MySQL Insert with While Loop

Upvotes: 3

user6214813
user6214813

Reputation:

Here is the script u want. i did it in php

<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";

// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $con->connect_error);
} 

echo "Connected successfully";

for ($i = 100; $i <= 450; $i++) {
 $sql="insert into student(rollno) values('$i')";
    $result=mysqli_query($con,$sql);
}
mysqli_close($con);
?> 

don't forget to enter username,password etc.. then save this in a .php file and run it

Upvotes: -2

Related Questions