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";
}
?>
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 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;
}
}
another empty row with timestamp added in mysql database each time a new row with entries added ,
here is part of my code
$servername = "localhost";
$username = "root";
$password = "zaheer442";
$dbname = "76H";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
$sql = "INSERT INTO 76Hlog (Device_ID, Response_status, Device_NO, Status, Time) VALUES ('$keywords[4]', '$keywords[8]', '$keywords[15]', '$keywords[17]', now())";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
//displaying data
$sql = "SELECT Device_ID, Response_status, Device_NO, Status FROM 76H";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["Device_ID"]. " - Staus: " . $row["Response_status"]. " Devic No " . $row["Device_NO"]. " Mode " . $row["Status"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
[Entries Screenshot has also attached]
So i've been trying to sort this issue out for a while but been unable to figure out if i have to do this trough SQL side or the PHP side.
My code i have so far:
<?php
$servername="";
$username = "";
$password = "";
$dbname = "alphacre_kingsland";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `bm_player_bans` ORDER BY id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$playerId = bin2hex($row['player_id']);
$storedname= getPlayerName($playerId);
$sql = "INSERT INTO bm_onlinedata (uuid, playername) VALUES ('".$playerId."', '".$storedname."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}else{
echo "0 results";
}
mysqli_close($conn);
function getPlayerName($uuid){
$json_response = file_get_contents("https://sessionserver.mojang.com/session/minecraft/profile/".$uuid);
$data = json_decode($json_response);
return $data->name;
}
?>
So this stores "UUID" and playername into a seperate table. But i want to check if the UUID is already in there before it adds a new one. Basicly updating it.
This is because playernames can change. And i don't want multiple rows of the same data.
But thats ONLY if its there ofc.
Background information:
I'm fetching the username from a user trough Mojangs API, wich only allows a single lookup of that UUID every minute. So i want to get the data every 5 minutes or so using a scheduled task running this script and store it in a table.
You can easily check with select
$sql = "SELECT * FROM `bm_player_bans` ORDER BY id";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$playerId = bin2hex($row['player_id']);
$storedname= getPlayerName($playerId);
$sql = "SELECT * FROM `bm_onlinedata` where uuid = '" . $playerId ."';";
$result = mysqli_query($link, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows> 0) {
$sql = "UPDATE bm_onlinedata
set playername = '". $storedname."'
where uuid = '" .$playerId ."';"; )";
} else {
$sql = "INSERT INTO bm_onlinedata (uuid, playername) VALUES ('".$playerId."', '".$storedname."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
}else{
echo "0 results";
}
I read in data from a csv file, and want to insert it into my database. The issue is that it only inserts the last row in the CSV file each time. However when i print my $sq1 to screen it shows all 48 inserts with the different values that they should have. Could anyone tell me why it only inserts one row into the database?
<?php
// Did modify login values for privacy
$servername = "10.100.";
$username = "myusername";
$password = "abc123";
$dbname = "informationdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = fopen("ALMGrade.csv","r");
while(! feof($file)){
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
}
fclose($file);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
move the execution of query ($conn->query($sql) ) inside while:
while(! feof($file))
{
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
fclose($file);