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.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
to explain my question better, i have two files: dbh.inc.php
$dbServername = "localhost";
$dbUsername = "xxxxx";
$dbPassword = "secret";
$dbName = "databasename";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
mysqli_set_charset($conn,"utf8");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
$table1 = "users";//1
$table2 = "userprofile";//2
$table3 = "twofactorauth";//3
And: database-query.func.php
function selectdb($data, $values, $url) {
include ('dbh.inc.php');
extract($data);
extract($values);
switch ($data['table']) {
case '1':
$table = $table1;
break;
case '2':
$table = $table2;
break;
case '3':
$table = $table3;
break;
}
$sql = "SELECT $rows FROM $table WHERE $where;";
print_r($sql);
die();
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_close($stmt);
mysqli_close($conn);
header("Location: ".$url."?error=sqlerror");
die();
} else {
$amount = str_repeat('s', count($values));
$values = array_values($values);
mysqli_stmt_bind_param($stmt, $amount, ...$values);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$getResult = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);
mysqli_close($conn);
$new = array_push($getResult, 'true');
return $getResult;
}
}
So the first holds database connection, and the latter has dynamic querys for insert, update and select for the moment. And i am wondering should i combine the two files, to one. Since every time i need my connect i always use one of my querys and same on the other way around?
Also 2 bonus questions: as you see in my connect file i have my table names and i use numbers in my other files and in the functions connect numbers to names.
Lastly should i use PDO, why?
To answer your question in general - yes, you can put a helper function in the same file where sql connection is made.
However, the code of your actual function is questionable at the very least. Or, to tell you truth, your function selectdb() is a torture for a programmer and shouldn't be stored anywhere. Stick to natural SQL queries written as is. You don't need numbers to represent tables. You don't need $rows variable. Everything could be written right in the SQL string. All you will need is a simple helper function that would reduce the amount of code required to run a query.
Here is an example of such mysqli include file
Once it's included in in your script, you can use it to run any mysql query, to any table, with any list of variables. Check out the following example (you can copy and paste the following code block to your file and run it as is):
<?php
require 'mysqli.php';
#Create a temporary table
$conn->query("CREATE temporary TABLE tmp_mysqli_helper_test
(id int auto_increment primary key, name varchar(9))");
# populate it with sample data
$sql = "INSERT INTO tmp_mysqli_helper_test (name) VALUES (?),(?),(?)";
$stmt = prepared_query($conn, $sql, ['Sam','Bob','Joe']);
echo "Affected rows: $stmt->affected_rows\n";
echo "Last insert id: $conn->insert_id\n";
# Getting rows in a loop
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id > ?";
$res = prepared_query($conn, $sql, [1])->get_result();
while ($row = $res->fetch_assoc())
{
echo "{$row['id']}: {$row['name']}\n";
}
# Getting one row
$id = 1;
$sql = "SELECT * FROM tmp_mysqli_helper_test WHERE id=?";
$row = prepared_query($conn, $sql, [$id])->get_result()->fetch_assoc();
echo "{$row['id']}: {$row['name']}\n";
# Update
$id = 1;
$new = 'Sue';
$sql = "UPDATE tmp_mysqli_helper_test SET name=? WHERE id=?";
$affected_rows = prepared_query($conn, $sql, [$new, $id])->affected_rows;
echo "Affected rows: $affected_rows\n";
# Getting an array of rows
$start = 0;
$limit = 10;
$sql = "SELECT * FROM tmp_mysqli_helper_test LIMIT ?,?";
$all = prepared_query($conn, $sql, [$start, $limit])->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($all as $row)
{
echo "{$row['id']}: {$row['name']}\n";
}
As you can see, a proper helper function can keep all the flexibility and readability of SQL and reduce the amount of code at the same time.
I've been spending a couple of hours trying to write mysqli queries to insert a new row in a database (with a primary key ID) and then select the ID of the new row. My code as it currently is:
<?php
include('connectionData.php');
$conn = mysqli_connect($server, $user, $pass, $dbname, $port)
or die('Connection error');
if(isset($_POST['submit'])) {
$pnum = $_POST['pnum'];
$phone_insert_text = "INSERT INTO `voterdatabase`.`phone` (`pnum`) VALUES (?)";
$phone_insert_query = $conn->prepare($phone_insert_text);
$phone_insert_query->bind_param('s', $pnum);
$phone_insert_query->execute();
$phone_select_text = "SELECT phone_id FROM voterdatabase.phone WHERE pnum=?";
$phone_select_query = $conn->prepare($phone_select_text);
$phone_select_query->bind_param('s', $pnum);
$phone_select_query->execute();
$phone_select_query->bind_result($phone_id);
echo $phone_id;
?>
$phone_insert_query executes without issue. But $phone_select_query doesn't appear to run at all, as echo $phone_id; has no effect. What might be going on here? I'm able to run the query directly in MySQLWorkbench.
Note that I previously tried doing this in one query using SELECT LAST_INSERT_ID();, but mysqli fails to execute any query containing that.
Please try this
$lastInsertID= mysqli_insert_id($conn);
Use insert_id property:
<?php
include('connectionData.php');
$conn = mysqli_connect($server, $user, $pass, $dbname, $port)
or die('Connection error');
if(isset($_POST['submit'])) {
$pnum = $_POST['pnum'];
$phone_insert_text = "INSERT INTO `voterdatabase`.`phone` (`pnum`) VALUES (?)";
$phone_insert_query = $conn->prepare($phone_insert_text);
$phone_insert_query->bind_param('s', $pnum);
$phone_insert_query->execute();
$phone_id = $conn->insert_id;
echo $phone_id;
?>
If you wish to be able to use the available functions to get the last inserted id, like mysqli_insert_id(), your table must have an AUTO_INCREMENT column. If not you will not get the id.
Also, even if you have the required columns, this will require two calls. To get around this, what you could do is something like create a stored procedure to do your insert for you and return the inserted id from the procedure.
This question already has answers here:
How do I get the last inserted ID of a MySQL table in PHP?
(16 answers)
Closed 7 years ago.
I'm inserting a row in the following way:
require("localhost_credentials.php");
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$q_title = $fixed_title;
$q_tags = $_POST['tag_input'];
$q_mod = "n";
$q_t_create = date("m/d/Y # G:i:s");
$q_t_modified = date("m/d/Y # G:i:s");
$querystr = "INSERT INTO mytable (title, tags, moderator, time_created, time_last_modified) ";
$querystr .= "VALUES (?, ?, ?, ?, ?);";
$statement = $conn->prepare($querystr);
$statement->bind_param("sssss", $q_title, $q_tags, $q_mod, $q_t_create, $q_t_modified);
$statement->execute();
I would like to get the id of the row I just inserted without having to do a second query. I've seen a few methods to do this on SO, but every time there's a debate as to which way it should and should not be done and I'm kind of confused.
Using prepared statements, how do I get the id of a newly inserted row using only one query?
As long as you do not execute multi insert, you can use
$conn->insert_id
It is populated automatically when a statement created from that connection executes INSERT query.
you can use something like this :
$last_id = $statement->insert_id($conn);
this will return the last inserted row id .
This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";
Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source