I am trying to insert multiple times an array that can have from 3 to 6 int inside it.
I created this to solve the problem:
CREATE TABLE name(
ID INT AUTO_INCREMENT NOT NULL,
NUM1 INT NOT NULL,
NUM2 INT NOT NULL,
NUM3 INT NOT NULL,
NUM4 INT,
NUM5 INT,
NUM6 INT,
PRIMARY KEY(ID)
)DEFAULT CHARSET = latin1;
On top of that I created the following code so I could insert the data. It receives $num - a int where tells how many numbers will have that aren't NULL and an array with the ints.
function inserDataBase($num,$array)
{
$x = array();
$x[0] = NULL;
$x[1] = NULL;
$x[2] = NULL;
$x[3] = NULL;
$x[4] = NULL;
$x[5] = NULL;
for($i=0;$i<$num;$i++){
$x[$i] = $array[$i];
}
//connetion to the Server
$username = "root";
$password = "";
$hostname = "localhost";
$database = "tournament";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$conn = mysql_select_db($database)
or die("Unable to connect to the selected database");
$sql = "INSERT INTO 'name' VALUES ($x[0], '$x[1]', '$x[2]', '$x[3]', '$x[4]', '$x[5]')";
mysql_query($sql,$dbhandle)
or die(mysql_error());
mysql_close($dbhandle);
}
Problems that I am getting:
I can't insert them at all. I searched a bit and I know now that SQL doesn't understand variables and I need to change that to something else but i am worried if I pass them to ints and the NULL give me some kind of trouble.
This is a inside database, I mean it is just random numbers that are going to inserted. Should I be worried about SQL injection or no?
This is a aux function so I was wondering if it was better to start the connection and close it on the end or create a single connection for each time for each insertion of data.
By putting single quotes around the inserted values, you are changing them to a string - so you won't get the record inserted.
Edit: Also, in MySQL you don't put single quotes around column names, you use a backtick ` character. I have updated all but the initial SQLs to show this.
If you change the variable in the PHP code to $x[0] = 'NULL'; you will then be able to insert a null value into a column with this:
$sql = "INSERT INTO 'name' VALUES ($x[0], $x[1], $x[2], $x[3], $x[4], $x[5])";
The code you originally had was being parsed like this:
INSERT INTO `name` VALUES (1, 2, 3, '', '', '')
Where now that the variables are being set as a string initially, the SQL will be parsed as this:
INSERT INTO `name` VALUES (1, 2, 3, null, null, null)
Edit: Having said that, I do think that one of the comments is correct, you can't parse arrays inside a string, so your code would need to look like:
$sql = "INSERT INTO `name` VALUES (".$x[0].", ".$x[1].", ".$x[2].", ".$x[3].", ".$x[4].", ".$x[5].")";
This code works. Has all the above modifications, but also includes a loop to create the sql query.
$array = array(1,2,3);
$num = count($array);
inserDataBase($num,$array);
function inserDataBase($num,$array)
{
for($i=0;$i<$num;$i++){
if $x[$i] = $array[$i];
}
for($i=$num;$num<=5;$i++){
if $x[$i] = NULL;
}
//connetion to the Server
$username = "root";
$password = "";
$hostname = "localhost";
$database = "tournament";
$dbhandle = mysqli_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$conn = mysqli_select_db($dbhandle,$database) or die("Unable to connect to the selected database");
$sql = "INSERT INTO name VALUES (''";
$count = 0;
$values = '';
for($count=0;$count<=5;$count++){
$values .= ",".$x[$count];
}
$sql .= $values . ")";
echo $sql;
mysqli_query($dbhandle,$sql) or die(mysql_error());
mysqli_close($dbhandle);
}
Related
I'm trying to send form data to MySQL. I've found tonnes of code on the net, so I'm copying, and pasting and creating PHP scripts and adding them to my phpAdmin, but I really have no idea.
I don't know what to add to my form as an action to tell the form to send the data to my database. I already have an action code in the form, am I able to have two?
I have created a table in my phpAdmin, but I don't know if it actually will work.
This is my PHP code that I have stuck in my public_html folder, with generic username, database name, and password. I use an IP address instead of Localhost, as this database is on the Internet through Bluehost rather than my own computer.
<?php
// This function will run within each post array including multi-dimensional arrays
function ExtendedAddslash(&$params)
{
foreach ($params as &$var) {
// check if $var is an array. If yes, it will start another ExtendedAddslash() function to loop to each key inside.
is_array($var) ? ExtendedAddslash($var) : $var=addslashes($var);
}
}
// Initialize ExtendedAddslash() function for every $_POST variable
ExtendedAddslash($_POST);
$submission_id = $_POST['submission_id'];
$name = $_POST['name'] ;
$email = $_POST['email'] ;
$homeclub = $_POST['homeclub'] ;
$course1 = $_POST['course1'] ;
$course2 = $_POST['course2'] ;
$winner = $_POST['winner'] ;
$db_host = 'localhost';
$db_username = 'userrname';
$db_password = '';
$db_name = 'dbName';
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
// search submission ID
$query = "SELECT * FROM `table_name` WHERE `submission_id` = '$submission_id'";
$sqlsearch = mysql_query($query);
$resultcount = mysql_numrows($sqlsearch);
if ($resultcount > 0) {
mysql_query("UPDATE `table_name` SET
`name` = '$name',
`email` = '$email',
`homeclub` = '$homeclub',
`course1` = '$course1',
`course2` = '$course2'
`winner` = '$winner'
WHERE `submission_id` = '$submission_id'")
or die(mysql_error());
} else {
mysql_query("INSERT INTO `table_name` (submission_id, formID, IP,
name, email, homeclub, course1, course2, winner)
VALUES ('$submission_id', '$formID', '$ip',
'$name', '$email', '$homeclub', '$course1', '$course2', '$winner') ")
or die( mysql_error());
}
?>
Any assistance will be greatly appreciated.
I'm sorry but your code is very outdated. You need to validate your value in case something is missing. I used Nulls coaling to do this (-> ?? ""), then you use mysql. You could use mysqli but I prefer and recommend PDO because it's easier. And instead to ask database if there is an insert first, just say hey update if there is an insert with the same id, or insert is (that makes Replace). But in order to do this, make submission_id unique in database
https://joshuaotwell.com/use-mysql-unique-constraint-in-phpmyadmin/
PS: this code is not tested but it should work, otherwise send me your full error report message
<?php
// read variables or assign them a default value
$submission_id = $_POST['submission_id'] ?? 0;
$name = $_POST['name'] ?? "";
$email = $_POST['email'] ?? "";
$homeclub = $_POST['homeclub'] ?? "";
$course1 = $_POST['course1'] ?? ""; // make array out of this
$course2 = $_POST['course2'] ?? "";
$winner = $_POST['winner'] ?? "";
// mysql is deprecated use pdo instead
$pdo = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_username, $db_password)
// if exists -> replace, if not exist insert (replace makes that in one query)
// submission_id must be flagged as unique in mysql otherwise it will insert a new row every time
// I use prepared statements so first tell database what to do then the value
// prevents hacking and increase secureity
$query = 'REPLACE table_name SET
name = :name
, email = :email
, homeclub = :homeclub
, course1 = :course1
, course2 = :course2
, winner = :winner
, submission_id = :submission_id';
$statement = $pdo->prepare($query);
$statement->execute(array(
':name' = $name
, ':email' = $email
, ':homeclub' = $homeclub
, ':course1' = $course1
, ':course2' = $course2
, ':winner' = $winner
, ':submission_id' = $submission_id
));
I am trying to create a temptable and do some calculations that populates the temptable and finally get the results from the created temp table. But so far I have been unsuccessful. My query is a little bit more involved but here is the thing that I am trying to do. This code assumes we have database connection set up with codeigniter.
-- This generate no results i.e. Array ()
$sql = "CREATE TABLE #output(name varchar NULL, id int NULL);
insert into #output (name,id) VALUES('sam',5)
SELECT * FROM #output";
$res = $this->db->query($sql);
--Also tried this and returns nothing
$queryList = [
'sql1' => "IF OBJECT_ID('tempdb.dbo.#output', 'U') IS NOT NULL DROP TABLE #output;",
'sql2' => "CREATE TABLE #output(name varchar NULL, id int NULL);",
'sql3' => "insert into #output (name,id) VALUES('sam',5)",
'sql4' => "SELECT * FROM #output"
];
$result = array();
foreach($queryList as $key => $value){
$result[$key] = $this->db->query($value, FALSE, TRUE);
}
These two were written to use codeigniter db drivers. None of the above queires even resulted in #output temptable in the tempdb of the database.
I also tried using sqlsrv_query directly, this one at least created the #output temptable but did not give me any results back.
-- Created the #output temptable but didn't give me back the data inserted
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
$sql = "CREATE TABLE #output(name varchar NULL, id int NULL);
insert into #output (name,id) VALUES('sam',5)
SELECT * FROM #output
--DROP TABLE #output";
$stm = sqlsrv_query($conn, $sql,[]);
while( $obj = sqlsrv_fetch_object( $stm )) {
echo $obj->name . '<br />';
//print_r($obj);
}
I have been trying a lot of scenarios but couldn't figure out what is wrong with my code. Oh BTW I also tried codeigniter trans_start() and end and added every query as a separate query but that didn't work out either. I couldn't think or search anything else and so here is my request for a help.
Here is my environment:
SQLSRV 5.3
SQL server 2012
ODBC Driver 17
CodeIgniter 3.1.9
PHP 7.0.31
Solution:
You need to fix some issues:
define varchar columns with this format: varchar [(n|max)]. When n is not specified, the default length is 1 and when you try to INSERT value 'sam', a warning will be generated.
put SET NOCOUNT ON; as first statement. If you miss that part, your statement will return more than one resultset, so you must make resultsets available by using sqlsrv_next_result().
Working example:
<?php
$server = 'server\instance,port';
$database = 'database';
$username = 'username';
$password = 'password';
$cinfo = array(
"Database" => $database,
"UID" => $username,
"PWD" => $password
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false) {
echo print_r(sqlsrv_errors(), true);
exit;
}
# Statement
$sql = "
SET NOCOUNT ON;
CREATE TABLE #output(name varchar(50) NULL, id int NULL);
INSERT INTO #output (name, id) VALUES ('sam', 5);
SELECT * FROM #output;
";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
echo print_r(sqlsrv_errors(), true);
exit;
}
# Results
while ($obj = sqlsrv_fetch_object($stmt)) {
echo 'Name: '.$obj->name.'</br>';
echo 'ID: '.$obj->id.'</br>';
}
# End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
Notes:
I'm not so familiar with CodeIgniter, but I think that this is your problem.
I am a beginner of the program.
I am trying to use a PHP variable written in a MySQL table, but it is not recognized as a variable in PHP.
I made a table to test using this code
CREATE TABLE test_table (
'id' INTEGER,
'col_1' TEXT
);
And insert data;
INSERT INTO test_table VALUES('1', '$var');
I`ve tried to test using simple PHP code;
<?php
$server = 'localhost';
$user = 'root';
$password = '1111';
$database = 'test_database';
$conn = mysqli_connect($server, $user, $password, $database);
$sql = "SELECT * FROM test_table";
$table = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($table)) {
$var = 1;
echo $rows['col_1'];
}
?>
I expected the result will be '1' but actual result was '$var'.
How can MySQL data be recognized as a PHP variable?
Instead of using
echo $rows['col_1'];
use like this
$result=$query->result_array();
echo $result;
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.
I have a mysql table like this (sql):
CREATE TABLE IF NOT EXISTS silver_and_pgm (
_metal_name varchar(30) NOT NULL,
_bid varchar(30) NOT NULL,
_change varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table silver_and_pgm
INSERT INTO silver_and_pgm (_metal_name, _bid, _change) VALUES
('Silver\r\n', '555', '-0.22\r\n'),
('Platinum\r\n', '555', '-9.00\r\n'),
('Palladium\r\n', '555', '0.00\r\n'),
('Rhodium\r\n', '555', '0.00\r\n');
and i am using the following code to update a row which contains metal_name as Silver
<?php
$username = "root";
$password = "1234";
$database = "kitco";
$con=mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$bid = '101010';
$metal_name = 'Silver';
$query = "update silver_and_pgm set _bid='$bid' where _metal_name='$metal_name'";
//$query2 = "update silver_and_pgm set _bid='444'";;
echo $query."<br>";
$result = mysql_query($query);
if(!$result)echo "error";
?>
but $query doesn't work . it works fine if I use $query2 . If I use the same query directly in SQL of phpmyadmin result is same.
what is the problem with $query . I think its correct.
Would anybody please find the bug ??
It looks like you have a line break in your _metal_name in the database, the SQL query says Silver\r\n.