I am trying to add random x and y values to a MySQL database but strangely it only seems to ever add one value. I was looking at many of the other posts of similar issues on Stackoverflow and it just seemed they did not have query within the loop was the common issue. I do have the query in the loop and am unsure why it is still not working.
Please see my code below:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
I edited your for loop to look something like this, and it worked perfectly fine for me.
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y) VALUES ('$x', '$y')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Successfully created record " . $i;
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
ob_start();
ob_flush();
flush();
usleep(001000);
ob_flush();
flush();
}
it Delay's the loop by just a little like a fifth of a second in total. The reason I have delayed the iteration is because your database might have a limit on how many queries can be sent within a time frame. It works for me let me know if it works for you.
Create the values array in the for loop, then use implode to build the query outside the loop.
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO data (x, y) VALUES ";
$values = [];
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$values[] = "($x, $y)";
}
$query = $sql . implode(",", $values) . ";";
$r = $conn->query($query);
if ($r) {
echo "New records created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->connect_error;
}
$conn->close();
You are just running a single query for each loop. No need for multi query
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if (mysqli_query($conn,$sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
Related
Just the last data enters mysql with this program :
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Would you have a solution for this basic concern , thank you very much
the reason for your actual problem is
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
}
so you overwrite your $sql variable each time, and at the end of the loop you are left with the last value. but see the comments for the various issues/suggestions with this code
Edit: 5th Mar 2019
issue with your code was, since within for loop $sql always gets overwritten only the final $sql is executed.
As pointed out by #jameson2012, one optimum way to do this would be,
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
$values = [];
foreach ($a as $v) {
echo $v . "<br />\n";
$values[] = "('$v')";
}
$sql = "INSERT INTO Donnesmi (commentaire) VALUES " . emplode(',', $values);
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
basically rather than running multiple insert statements, you build a one single statement and execute it.
========================================================================
Old Answer
You must execute SQL inside foreach. Refer below.
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
I am trying to use a FOREACH loop to query a database based on each value in the $userid array below. I am also looping through the $grade array as I need the corresponding value for the sql query to then put into a HTML table.
//Decode JSON file to an Object
$json_d = json_decode(file_get_contents("results.json"));
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<table><tr><th>First Name </th><th>Last Name </th><th>Grade </th></tr>";
foreach($userid as $id) {
foreach($grade as $grd) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["firstname"]. "</td><td>" . $row["lastname"]. "</td><td> " . $grd . "</td></tr>";
}
} else {
echo "ERROR!";
}
}
}
echo "</table>";
mysqli_close($conn);
I have checked the $grade and $userid array and they do contain the correct values however running the PHP file I only get the first record outputted in the table. E.G.
FirstName LastName Grade
Student 1 85
Whereas I need the other 2 records that are supposed to appear.
I've got a script that opens 6 MySQL queries in 1 php page. here's the script:
if(!isset($_SESSION["name"]) || empty($_SESSION["name"])) {
header("Location: http://www.google");
die();
} else {
$servername = "localhost";
$username = "user";
$password = "123";
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername, $username, $password);
$conn3 = new mysqli($servername, $username, $password);
$conn4 = new mysqli($servername, $username, $password);
$conn5 = new mysqli($servername, $username, $password);
$conn6 = new mysqli($servername, $username, $password);
if ($conn4->connect_error) {
die("Connection failed: " . $conn4->connect_error);
}
$sql4 = "SELECT * FROM tableT WHERE date(ftdate) = curdate()";
$result4 = $conn4->query($sql4);
$row4 = $result4->fetch_assoc();
$conn4->close();
date_default_timezone_set("Asia/Kuala_Lumpur");
if ($result4->num_rows < 1) {
if ($conn3->connect_error) {
die("Connection failed: " . $conn3->connect_error);
}
$date = date("Y-m-d");
$sql3 = 'INSERT INTO tableT (`id`, `date`) VALUES (Null, "' . $date . '")';
if ($conn3->query($sql3) === TRUE) {
header("Location: http://google.com");
die();
} else {
echo "Error: " . $sql3 . "<br>" . $conn3->error;
}
$conn3->close();
} Else {
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql = "SELECT * FROM tableB WHERE something = '0'";
$sql2 = "SELECT * FROM tableP WHERE id=1";
$result = $conn->query($sql);
$conn->close();
$result2 = $conn2->query($sql2);
$row2 = $result2->fetch_assoc();
$conn2->close();
if ($conn5->connect_error) {
die("Connection failed: " . $conn5->connect_error);
}
$month = date("m");
$sql5 = "SELECT * FROM tableB WHERE month(date) = '" . $month . "' AND something = '1' ORDER BY fid";
$result5 = $conn5->query($sql5);
if ($result5->num_rows > 0) {
$x = 1;
$monthlyt = 0;
$y = 0;
$dailyt = 0;
$day = date("Y-m-d");
while($row5 = $result5->fetch_assoc()) {
$monthlyt = $row5[ftotal] + $monthlyt;
$x = $x + 1;
$dbdate = date("Y-m-d", strtotime($row5[fdate]));
if ($dbdate == $day) {
$y = $y + 1;
$dailyt = $row5[total] + $dailyt;
}
}
$damount = ($y / $row2[something]) * 100;
$dtotal = ($dailyt / $row2[some]) * 100;
$mtotal = ($monthlyt / $row2[blah]) * 100;
}
$conn5->close();
if ($conn6->connect_error) {
die("Connection failed: " . $conn6->connect_error);
}
$sql6 = 'UPDATE tableT SET something="' . $y . '", some="' . $blah. '" WHERE tdate="' . $day . '"';
if ($conn6->query($sql6) === TRUE) {
//done
} else {
echo "Error: " . $sql6 . "<br>" . $conn6->error;
}
$conn6->close();
}
}
this page loads a dashboard showing a few different tables and some average response time calculations.
it was working previously, but I got an error saying "website redirected you too many times" Try clearing your cookies. ERR_TOO_MANY_REDIRECTS from chrome today.
So i'm thinking, is there a way I can simplify this? or would this lead to errors?
I wrote the following code:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
echo $result;
if ($result > 0) {
$result = $result + 1;
$sql2 = "UPDATE Eshop SET quantity = $result WHERE id = $insert";
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ($insert, 1)";
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
?>
What I want this script to do is select the quantity where the id is $insert and then if quantity > 0, add 1 to the quantity and update the quantity, if not insert the id and quantity = 1 into the table. The table has only two fields id(VARCHAR(32)) and quantity(DECIMAL(8,1)). I tried to do it more general in order to help as many people as possible. Could you please help me? Thanks in advance. NOTE: When I run the script in the browser(after uploading it to the server with the correct username,domain etc.) nothing shows up and I dont even get an error in the console.
You need to extract the result of your query and loop through each row:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$sql2 = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($sql2) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($sql3) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
}
?>
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
//check if particular record exists or not
$count=mysql_num_rows($result);
if($count>0) // if records exists for the particular id
{
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$update = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($update ) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $update . "<br>" . $conn->error;
}
} else {
$insert = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($insert ) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert . "<br>" . $conn->error;
}
} // else qty is <=0
} //end while
}
else {
echo "Records do not exists for that particular id";
}
?>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
<?php
function db_query()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "single4thenight";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, alias, type, parent, ordering, published FROM iutca_jomcl_locations"; //selects locations from
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " alias" . $row["alias"]. " type: " . $row["type"]. " - parent: " . $row["parent"]. " ordering " . $row["ordering"]. "published " . $row["published"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
}
function read_location()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "single4thenight";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM iutca_jomcl_locations"; //selects locations from
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
// echo "Location : " . $row["name"]."<br>";
$row_name = $row["name"];
echo $row_name.'<br />';
}
}
$file1 = "./location.txt";
$lines = file($file1);
foreach($lines as $line_num => $line)
{
echo $line;
}
}
My location.txt file contains this
Auburn
Birmingham
Dothan
Gadsden
Huntsville
Mobile
Montgomery
Muscle Shoals
Tuscaloosa
I would like to compare my sql database with txt file to make sure that i do not arealdy have variables inside. I do not want to put duplicates in side my sql i would like to know what is the easiest way to update my sql
You could use INSERT IGNORE INTO instead of just INSERT INTO and MySQL will then ignore duplicate entries. See the MySQL documentation for INSERT for more information. So, based on what I see in your question, your SQL would look something like:
INSERT IGNORE INTO iutca_jomcl_locations ('name') values (?)
Hope this helps! :)
First we read file content to the $content variable
$content = file('mytxt.txt')
As you posted, your file contains words separated with space (if not, skip this and make variable $words contain values you need) so we need to split content, to get each word as array item
$words = explode(" ", $content);
Finally, inserting value and checking if there is one like that existing in DB
foreach($words as $word)
{
$sql = "INSERT iutca_jomcl_locations (name)
SELECT $word
WHERE NOT EXISTS
( SELECT 1
FROM tblSoftwareTitles
WHERE name = $word
);"
$result = $conn->query($sql);
}
iutca_jomcl_locations - table name
name - column to insert (also checking for unique values using this column)
I used This Code and it Worked for me
foreach($lines as $line_num => $line)
{
$line = $line;
//echo $line;
$sql = "SELECT ordering, name FROM iutca_jomcl_locations WHERE name='$line'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
echo "Found Locations: " . $row["name"]." The ordering Number Is " . $row["ordering"]."<br>";
$ordering =$row["ordering"];
}
} else {
if($ordering >=0)
{
$count = $ordering;
//echo "0 results";
$lowerCase = strtolower($line);
$sql = "INSERT INTO iutca_jomcl_locations (name, alias , parent, published,ordering)
VALUES ('$line','$lowerCase','$parent','1','$count')";
$count = $count + 1;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br />";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
}