Mysqli can't insert multiple rows - php

$allgames = file_get_contents("https://steamspy.com/api.php?request=all");
$decodeall = json_decode($allgames, true);
foreach($decodeall as $game) {
$sql = "INSERT INTO games (name)
VALUES ('{$game['name']}')";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
When i do this only the first row will be added. How do i insert multiple rows?

Just get rid of that multi query thing. Use a prepared statement instead
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach($decodeall as $game) {
$name = $game['name'];
$stmt->execute();
}
echo "New records created successfully";
Note that your current code with multi_query won't work as intended anyway, even with that silly typo fixed. You will have the result of only first query, having no idea what happened to all others.

You are overwriting the query each time. Try setting sql to blank then appending it each time in the loop.
Try this:
$sql = array();
foreach($decodeall as $game) {
$sql[] = "INSERT INTO games (name) VALUES ('{$game['name']}')";
}
$sqlInserts = implode(';', $sql);
if ($conn->multi_query($sqlInserts) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

You don't need to perform the query multiple times like that, you can do it all in a single query without multi_query(). You can perform many INSERTs with a single query, like this
// Initialize the query-variable
$sql = "INSERT INTO games (name) VALUES";
// Loop through results and add to the query
foreach ($decodeall as $game) {
$sql .= " ('".$game['name']."'),";
}
// Remove the last comma with rtrim
$sql = rtrim($sql, ',');
// Perform the query
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will generate a query resembling
INSERT INTO games (name) VALUES ('One'), ('two'), ('Three')
which will insert the values One, Two and Three into separate rows.
This query will break if your $game['name'] variables contain an apostrophy ', so at the very least you should use $mysqli::real_escape_string(), although a prepared statement takes care of that and prevents SQL injection (so I recommend you go for that instead). See How can I prevent SQL injection in PHP?
Using a prepared statement - the better solution
The preferred method of executing a query is by using a prepared statement.
Fetch all the columns using array_column() and loop the array while calling the execute method until finished.
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach (array_column($decode, "name") as $name) {
$stmt->execute();
}

Related

Correct way/location to use Scope_Identity()

I have an auto incrementing ID called deviceID in one of my fields. I was wanting to pass this to a session in php to use later on and was planning on using scope_identity() as I understand that this is the best way to get the current Primary key ID. However anytime I have attempted to use it I have had a error message saying that it is an undefined function. Here is my code so without the scope_identity():
<?php
session_start();
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["screenWidth"] = $screenWidth;
$_SESSION["screenHeight"] = $screenHeight;
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
$_SESSION["HandUsed"] = $HandUsed;
$_SESSION["phoneName"] = $phoneType;
echo 'hello';
$sql = "
INSERT INTO DeviceInfo (DeviceID, screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')
SELECT SCOPE_IDENTITY() as DeviceID
";
if (sqlsrv_query($conn, $sql)) {
echo ($sql);
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
?>
You need to fix some issues in your code:
The INSERT statement is wrong - you have five columns, but only four values in this statement. I assume, that DeviceID is an identity column, so remove this column from the column list.
Use parameteres in your statement. Function sqlsrv_query() does both statement preparation and statement execution, and can be used to execute parameterized queries.
Use SET NOCOUNT ON as first line in your statement to prevent SQL Server from passing the count of rows affected as part of the result set.
SCOPE_IDENTITY() is used correctly and it should return the expected ID. Of course, depending on the requirements, you may use IDENT_CURRENT().
The following example (based on the code in the question) is a working solution:
<?php
session_start();
include 'db.php';
if (isset($_POST['submit'])) {
$screenWidth = $_POST['screenWidth'];
$phoneType = $_POST['phoneName'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
$params = array($screenWidth, $phoneType, $screenHeight, $HandUsed);
$sql = "
SET NOCOUNT ON
INSERT INTO DeviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES (?, ?, ?, ?)
SELECT SCOPE_IDENTITY() AS DeviceID
";
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error: " . $sql . ": " . print_r(sqlsrv_errors());
exit;
}
echo "New record has been added successfully !";
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row["DeviceID"];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
?>

how to insert into database columns one after the other using php

I have three columns that I want to insert data into using php. the code will be run three times.
I want if run the code the first time to insert only on column1 while leaving other columns empty.
If run the second time to insert into only column2 while leaving other column empty
and so on. I have tried the code below but cannot get it to work. it only inserts into the column1
<?php
error_reporting(0);
include('db.php');
$result = $db->prepare('SELECT * FROM rec');
$result->execute(array());
while ($row = $result->fetch())
{
//$id = $row['id'];
$column1 = $row['column1'];
$column2 = $row['column2'];
$column3 = $row['column3'];
}
if ($column1 ==''){
echo 'empty';
$statement = $db->prepare('INSERT INTO rec(column1)
values(:column1)');
$statement->execute(array(':column1' =>'$column1'));
} elseif ($column2 ==''){
echo 'empty2';
$statement = $db->prepare('INSERT INTO rec (column2)
values(:column2)');
$statement->execute(array(':column2' =>'$column2'));
} elseif ($column3==''){
echo 'empty3';
$statement = $db->prepare('INSERT INTO rec(column3)
values(:column3)');
$statement->execute(array(':column3' =>'$column3'));
}
Firstly it is not a proper way of designing database.
Secondly, use if statements only rather than nested if-else statements and it will work!
Your if-else is such that the correct data is not getting inserted properly . Use the following code which will solve your purpose in your way . However , the way you are following is not correct . Either you follow the conventional way to create a database and inserting values into it or use dynamic fields for a table and insert it another way .
if ($column1 ==''){
echo 'empty';
}
else{
$statement = $db->prepare('INSERT INTO rec(column1)
values(:column1)');
$statement->execute(array(':column1' =>'$column1'));
}
if ($column2 ==''){
echo 'empty2';
}
else{
$statement = $db->prepare('INSERT INTO rec (column2)
values(:column2)');
$statement->execute(array(':column2' =>'$column2'));
}
if ($column3==''){
echo 'empty3';
}
else{
$statement = $db->prepare('INSERT INTO rec(column3)
values(:column3)');
$statement->execute(array(':column3' =>'$column3'));
}

PHP ~ Column count doesn't match value count at row 1

Am trying to insert into two tables but get this error
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
below is my insert code
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
but when i do some thing like this it works
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
i just change the $field1amount to $field2amount
but i dont want it that way i want to also get the value of $field1amount and insert it
please any help will be appriciated, thanks
The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.
Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();

cant insert data into existing table in mysql database with php

I get the message that the new record was created but when I reload phpmyadmin the table is the same. Also I have retrieved information from the same DB,
from the same table, with SELECT command, so the connection works..(plainly said). I have no clue why is not updating. Please help. Thank you in advance.
<html>
<head>
</head>
<body>
<?php
define('DB_NAME', 'appointments');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$hos=$_POST['hos'];
echo $hos;
echo "<br/>";
$doc=$_POST['doc'];
echo $doc;
$date=$_POST['fdate'];
echo $date;
$time=$_POST['time'];
echo $time;
$pat=5;
echo $pat;
$sql = "INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($link);
?>
</body>
</html>
There are many mistake in your code
1. use of mysql_error()
you can't use mysql_error because you use mysqli for data base connection.second thing mysql is no more supported
Solution use mysqli_error($link);
2. use of $conn->error
You can't us of $conn->error beacuse you connect with mysqli procedure way not like object oriented way and you also not define a $conn instead you used $link
Solution use mysqli_error($link);
Correct Code
if(!mysqli_query($link, $sql)){
printf("Errormessage: %s\n", mysqli_error($link));
die;
}else{
echo "New record created successfully";
}
Why Data Not Inserted
because you declare variable $sql but you didn't executed that
the new record was created
You get this message all ways because your if condition check that variable have a value (not 0) and yes $sql have value
1.You must use prepare statement,if you don't wan't any sql injection in insert statement SQL INJECTION
2.'' single quote or "" apply only on a string not on id if your app_id is a int don't use ('' or "") quote instead of that convert '4' to int
3.handle error log https://stackoverflow.com/a/3531852/3234646
4.Please clear Concept use of Database Extension
http://php.net/manual/en/class.mysqli.php
You forgot to execute the query, if ($sql) { merely evaluates the variable.
if (mysqli_query($link, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Also, you need to use backticks for SQL-related variables, not single quotes:
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');";
You're not actually executing your query. If you add the line $result = mysqli_query($link, $sql); after declaring $sql you will execute the query.
You can then assess whether it worked using the same if, but change that line to be
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
In the above example, I have also changed your error reporting as it was referencing $conn, a variable you had not declared before. It now uses the same $link variable as the rest of your code.
Also, I would highly recommend escaping your data since you're inserting the contents of posted data. Escaping your data will help protect against SQL Injection. It's not comprehensively safe, but it's a good start.
To add in escaping, change each $var = $_POST['var'] line to read $var = mysqli_real_escape_string($link, $_POST['var']);
For example, $hos=$_POST['hos']; becomes $hos = mysqli_real_escape_string($link, $_POST['hos']);
This helps prevent moments like this wonderful example by XKCD
1) Remove single quotes (') from column name to backtick (`)
2) Execute your query. You didn't executed.
3) If app_id column is auto incremented and primary key. Then, no need to pass value. Leave it blank.
<?php
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('','$pat','$date','$time','$hos','$doc');";
$query = mysqli_query($link,$sql) ;
if ($query) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Instead of
"INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');"
unquote the columns
"INSERT INTO rantevou (app_id, patient_id, date, time, hos, doc) VALUES ('4','$pat','$date','$time','$hos','$doc');"
or use backticks
"INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');"
you've forgot to execute your query
mysqli_execute($con, "INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc')");
EDIT: What luweiqi said: the statement has yet to be executed!
It seems like you know what you are doing. Are you sure that the paramaters here:
$sql = "INSERT INTO rantevou (**'app_id','patient_id','date','time','hos','doc'**) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
exactly match your column titles in your database?
Another good way to check your statements, is to go to phpmyadmin and go to the SQL notepad and enter the query with the same structure and see what is being returned.
Your query may be returning a message, but a message saying that it has failed... which would still trigger your echo "New record created successfully";
This is how i've structured my most recent insert to DB:
<?php
// to get data from android app
$gardenID=$_POST["gardenID"];
$vID=$_POST["vID"];
$quantity = $_POST["quantity"];
$timePlanted = date("Y/m/d");
// establishes connection to database
require "init.php";
echo "here";
echo $timePlanted;
echo $quantity;
$query = "insert into garden_veg (gardenID, vID, quantity, timePlanted) values ('".$gardenID."','".$vID."',
'".$quantity."', '".$timePlanted."' );";
$result = mysqli_query($con,$query);
$response = array();
$code = "addItem_success"; //changed code
$message = "Item(s) added!";
array_push($response,array("code" => $code, "message"=>$message));
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
First of all, don't use single quotes for column names, either use nothing or use backticks.
Secondly, you forgot to execute the query.
Also, using OOP is better.
Please try:
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
and
$query = "INSERT INTO rantevou (app_id,patient_id,date,time,hos,doc) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($mysqli->query($query)) echo "New record created";
else echo "Error: ".$mysqli->error;

if successfully insert into database, insert into another database PHP

$sql = "INSERT INTO nextofkin(username,password,contact,email) VALUES('$NOKUN','$NOKPW', '$NOKContact', '$NOKEmail')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO users(username,password,role) VALUES ('$NOKUN','$NOKPW', 'nextofkin')";
} else {
$check1='fail';
}
when i run this php only the first sql statement is inserted.
How can i make the second sql statement run when i inserted into the first sql statement?
As #Darren pointed out, you're not actually executing the statement, you're just updating the value of $sql.
$sql = "INSERT INTO nextofkin(username,password,contact,email) VALUES('$NOKUN','$NOKPW', '$NOKContact', '$NOKEmail')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO users(username,password,role) VALUES ('$NOKUN','$NOKPW', 'nextofkin')";
$conn->query($sql);
} else {
$check1='fail';
}

Categories