loop for to insert row in a mysql database with php - php

I have a for loop with php but is not working properly. Inside the for loop I have an "if" and an "else", but the loop stops iterate in the first "else" and should continue. Here is the code:
//counting the rows in database and the rows I want to insert
$total = count($rowToInsert); //for example 10 values
$totalDB = count($rowDB); // for example 5 values
// the for loop starts
for ($i=0; $i < $total; $i++){ //it should iterate until 10 values
if(isset($rowDB[$i])){ //change the first 5 values
$update = "UPDATE table SET name = '$name[$i]' WHERE ID = $rowToInsert[$i]";
$result = mysqli_query($con, $update);
} else { //it should iterate from sixth until tenth value
$insert = "INSERT INTO table (name) VALUES ('$name[$i]')";
$result = mysqli_query($con, $insert);
// here is the next code
$newTable = 'table'.$rowToInsert[$i];
$newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
$resultDB = mysqli_query($con, $newDB);
// select the DB
mysqli_select_db($con, $newTable) or die ("not found");
} //end of else
} //end of for
The thing is if the database contain 5 rows and I want to insert, for example, 10 rows, the code works updating the first 5 with the new value, then it jumps to the "else" and starts to iterate in the sixth value and it works, but the next values doesn't.
Any idea what i'm doing wrong? Thanks!
Hector

Ok I found the problem. In the else loop, when the iteration tries to select the database, for some reason it takes part of the name of the last iteration, so it couldn't find the database. The solution (maybe is not so clean) is connect and close the database connection in every iteration. The code stays like this:
//counting the rows in database and the rows I want to insert
$total = count($rowToInsert); //for example 10 values
$totalDB = count($rowDB); // for example 5 values
// the for loop starts
for ($i=0; $i < $total; $i++){ //it should iterate until 10 values
if(isset($rowDB[$i])){ //change the first 5 values
$update = "UPDATE table SET name = '$name[$i]' WHERE ID = $rowToInsert[$i]";
$result = mysqli_query($con, $update);
} else { //it should iterate from sixth until tenth value
// reconnect to db
$con = mysqli_connect($host, $user, $pass) or die ("unable to connect");
$db = "database";
$insert = "INSERT INTO table (name) VALUES ('$name[$i]')";
$result = mysqli_query($con, $insert);
// here is the next code
$newTable = 'table'.$rowToInsert[$i];
$newDB = "CREATE DATABASE $newTable CHARACTER SET utf8 COLLATE utf8_general_ci";
$resultDB = mysqli_query($con, $newDB);
// select the DB
mysqli_select_db($con, $newTable) or die ("not found");
//close the connection to db;
$con->close();
} //end of else
} //end of for
Thanks you all for inspiring the answer!
Hector

Related

counter ID number instead of random ID number?

Good day,
I have a problem and i dont know how to do a Counting id number instead of random numbers, please help me. Thank you.
My codes working on random id, but i want it in Counting number ID. Thanks
<?php
$hostname_conn = "localhost";
$database_conn = "user_id";
$username_conn = "root";
$password_conn = "";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn,$conn);
// run an endless loop
while(1) {
$randomNumber = mt_rand(10, 100);// generate unique random number
$query = "SELECT * FROM tblrand WHERE the_number='".mysql_real_escape_string ($randomNumber)."'"; // check if it exists in database
$res =mysql_query($query,$conn);
$rowCount = mysql_num_rows($res);
$id=$randomNumber;
// if not found in the db (it is unique), then insert the unique number into data_base and break out of the loop
if($rowCount < 1) {
$con = mysql_connect ("localhost","root");
mysql_select_db("user_id", $con);
$sql = "insert into tblrand(the_number) values('".$randomNumber."')";
mysql_query ($sql,$con);
mysql_close ($con);
break;
}
}
echo "IT-FORM" .$id;
?>
CASE 1: id generated by server-side
At server side, configure mysql database to generate sequential unique id. Add a field in your
table with auto-increment
https://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html as suggested by
#Londeren
Client side just manage insert query to save data in database (not ids, just data related to ids).
Generally this solution is preferable: even if you have many clients, the database will manage all
the query methodically and efficiently.
CASE 2: id generated by client-side (not preferable, use CASE 1 if possible. Included this in
the answer because your question started from here)
You get the last id from database, generate a new one (last id + 1), and insert new id in the
database.
Client side manage select id query, generate new id, and insert query. You take the
risk that other clients generate the same id simultaneously and insert it in the database.
Supposing at server-side is everything ok, code at client-side could be this:
<?php
$hostname_conn = "localhost";
$database_conn = "user_id";
$username_conn = "root";
$password_conn = "";
$conn = mysql_pconnect($hostname_conn, $username_conn, $password_conn) or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn,$conn);
// run an endless loop
$count=1;
while(1) {
$query = "SELECT * FROM tblrand WHERE the_number='".mysql_real_escape_string
($count)."'"; // check if it exists in database
$res =mysql_query($query,$conn);
$rowCount = mysql_num_rows($res);
// if not found in the db (it is unique), then insert the unique number into data_base and break
out of the loop
if($rowCount < 1) {
$con = mysql_connect ("localhost","root");
mysql_select_db("user_id", $con);
$sql = "insert into tblrand(the_number) values('".$count."')";
mysql_query ($sql,$con);
mysql_close ($con);
$count++;
break;
}
}
echo "IT-FORM" .$count;
?>

Double or more value inserted when insert query written inside another query result object

I have the code below which was written in php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * from table name";
$result = $conn->query($sql);
//the result count is 95142
while($row = $result->fetch_assoc()) {
$sql = "insert into table1 (column) values ('test')";
$result = $conn->query($sql);
}
$conn->close();
?>
Which inserting more than 100 000 data in table1 but if I try to limit the source query up to 30 000 it inserts correct count of data into table1.
i.e
$sql = "SELECT * from table name limit 10000";
Both the table are in same Database.
Even tried with mysql_connect & mysql_query() method also getting the same error. Also tried with another connection for insert query but issue exists.
If I try the code like this
$flag = 1;
while($row = $result->fetch_assoc()) {
$flag = $flag + 1;
}
echo $flag;
I am getting the result of 95142.
you must really use different variable names in the second query !!!
while($row = $result->fetch_assoc()) {
$sql2 = "insert into table1 (column) values ('test')";
$result2 = $conn->query($sql2);
}
and secondly, delete the previous rows before running script, and then check the count, it must work fine.
Change your variable name $result inside the while.
Ex:
while($row = $result->fetch_assoc()) {
$insertSQL = "insert into table1 (column) values ('test')";
$insertRow = $conn->query($insertSQL);
}
The value of $result has been changed when insert query is executed. Maybe this is main problem.

INSERT IGNORE INTO - Number of rows inserted [duplicate]

This question already has answers here:
How to test if a MySQL query was successful in modifying database table data?
(5 answers)
Closed 1 year ago.
I'm going to insert about 500 records in a table using one query :
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`)
VALUES ('val1','val2') ('val3','val4') ... ";
// php_mysql_insert_function
How can I find out haw many rows are inserted in after executing query ?
The answer is affected_rows
$db = new mysqli('127.0.0.1','...','...','...');
$sql = "INSERT IGNORE INTO Test (id,test) VALUES (1,2),(1,3),(2,2),(3,4)";
$ins_test = $db->prepare($sql);
$ins_test->execute();
echo $db->affected_rows;
In this example Test has 2 columns id and test (both integer) and id is the primary key. The table is empty before this insert.
The programm echos 3.
Try this:
Procedural style of coding:
<?php
$host = '';
$user = '';
$password = '';
$database = '';
$link = mysqli_connect($host, $user, $password, $database);
if(!$link)
{
echo('Unable to connect to the database!');
}
ELSE {
$sql = "INSERT IGNORE INTO `table_name` (`field1`,`field2`) VALUES ('val1','val2'), ('val3','val4')";
$result = mysqli_query($link, $sql);
echo mysqli_affected_rows($link);
}
mysqli_close($link);
?>
mysqli_affeccted_rows counts the number of inserts. I think that #wikunia's answer will probably yield the same result. I was in the process of answering you question, before wikunia beat me to it. I place it anyway.

unable to insert records in database

starting query to display result:
$at = array();
$num=array();
$i=0;
while($rw=mysql_fetch_array($r))
{
echo $rw['c_number']
$number=$rw['c_number'];
$num[$i]=$number;
$i++;
echo $rw['total'];
$at[] = $rw['total'];
}
// the result of this query is like:
Mobile numbers bills
03455919448 34
03215350700 56
03474738923 678
03573987932 344
03187438979 1324
// now want to insert it in database
$d= 'november';
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at','$d','$num')";
mysql_error();
$result = mysql_query($sql);
}
// the insertion query at end is not working and gives me error:
MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0004 sec )
I think you need to replace num with num1 like
$sql = "INSERT INTO `billing details`(bill,`month/year`,c_number) VALES ('$at','$d','$num1')";
And dont use mysql_* functions due to they are depricated,instead you use mysqli_* functions or PDO statements
AND put your table name in '`' it seems like two different names and for the column name month/year also
i dont know what exactly want to insert $num or $num1 ? and check your table name ,column names
$d= 'november';
int i=0; // you are saying that $at has all bills
foreach($num as $num1){
$sql = "insert into billing details(bill,month/year,c_number) values ('$at[i]','$d','$num1[mobile_number]')";
$result = mysql_query($sql);
if (mysql_error()) die('Error, insert query failed');
i++;
}

SQL Query error in PHP

This is a code for a cafeteria, and this is the login.
<?php
$userna = 'root';
$paso = '';
$mach = 'localhost';
$db ='cafeteria';
session_start();
// GET PAGES RECORD FROM LOG TABLE: *********| Only the first time though:
if (isset($_SESSION['log']) != 'logging')
{
// Here, just creating a string:
$pages_record = "";
$insert_query = '';
// Get saved pages from the database:
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Error in log-page script: AB-1 - query: $insert_query." . mysqli_error($connection));
mysqli_select_db($connection,'cafeteria');
// Query string to pull all pages from table record:
$get_pages_query = "select * from log-page";
// Query the database, and save result:
$query_pages_result = mysqli_query($connection, $get_pages_query);
// Check number of results returned:
$num_of_results = '';
$num_of_results = mysql_num_rows($query_pages_result);
if ($num_of_results > 0)
{
// Loop through the result array: Each time, one row, and then the next one ...
for ($row = 0; $row < $num_of_results; $row++ )
{
// Getting one row:
$get_row = mysqli_fetch_array($query_pages_result);
// Extracting just the page name from the row:
$one_page = substr($get_row["page"],strripos($get_row["page"],"/") + 1);
// Adding this page name to the string created previously:
if ($row == 0)
{
$pages_record .= $one_page;
}
else
{
$pages_record .= ",".$one_page;
}
}
// Once all pages have been read and saved to the string
// now we save it to the session:
$_SESSION['logpages'] = $pages_record;
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
else
{
// There are no pages in the table:
$_SESSION['logpages'] = "";
$_SESSION['log'] = 'logging'; // This just tells us, we are logging pages to the database.
}
}
// Check if page is already in session list.
$pages_array = array();
if (strlen(isset($_SESSION['logpages'])) > 0 )
{
// string variable that holds all pages separated by commas:
$pages_string = $_SESSION['logpages'];
// creating an Array to hold all pages already logged in server:
if (strstr($pages_string, ","))
{
$pages_array = explode(",", $pages_string);
}
else // just means there's only one page in the record
{
// so, we push it inside the array.
array_push($pages_array, $pages_string);
}
// current page: [ We are extracting only the page, not the entire url, Exmp: login.php ]
$current_page = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Check if current_page is in the array already:
if (!in_array($current_page, $pages_array))
{
// IF is NOT in the array, then add it:
array_push($pages_array, $current_page);
// Add it to the Session variable too:
$pages_string = implode(",", $pages_array);
// Re-save it to SESSION:
$_SESSION['logpages'] = $pages_string;
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(`date`, `time`, `page`, `user`) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection, $insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
else
{
// IF it IS in the list, just SKIP.
}
}
else
{
// means, that there are absolutely no pages saved in the database, basically this is the first log:
$_SESSION['logpages'] = substr($_SERVER['PHP_SELF'],strripos($_SERVER['PHP_SELF'],"/") + 1);
// Now, add it to the database table "log-page""
$connection = mysqli_connect($mach,$userna,$paso,$db) or die ("Unable to connect!");
mysqli_select_db($connection,'cafeteria');
// Query to insert page description into the table:
// [ date - time - page - user ]
$insert_query = "INSERT INTO log-page
(date, time, page, user) VALUES
('".date("Y-m-d")."', '".date("H:i:s")."', '".$_SERVER['PHP_SELF']."', '".(isset($_SESSION['SESSION_UNAME']))."')";
mysqli_select_db($connection,'cafeteria');
// INSERTING INTO DATABASE TABLE:
mysqli_query($connection,$insert_query) or die ("Error in log-page script: AB-2 - query: $insert_query." . mysqli_error($connection));
// Done!
}
?>
But now i am getting this error:
Error in log-page script: AB-2 - query: INSERT INTO log-page (date,
time, page, user) VALUES ('2012-10-16', '16:58:44',
'/caf/pages/index.php', '').You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near '-page (date, time, page, user)
VALUES ('2012-10-16', '16:58:44' at line 1
Im using Xampp 1.8.1 PHP: 5.4.7. It does not let me login neither as administrator nor as a cashier
Enclose the table name in backticks like this (rest of the query omitted):
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) ... ";
Otherwise MySQL will try to interpret the - as a minus sign, which fails in this case.
EDIT
IN the last insert shown, also the column names should be enclosed in backticks:
$insert_query = "INSERT INTO `log-page` (`date`, `time`, `page`, `user`) VALUES ...";
Try escaping field name
(`date`, `time`, `page`, `user`)
It's been a while since I looked at mySql docs, but it looks to be complaining about the table name "log-page". Try quoting that table name.

Categories