PHP Not inserting record due to Null id - php

I want insert record into database using
I have 3 files
config.php (For database connection )
function.php (It's for create function of CRUD)
emp.php (Hear i called function from functions.php)
1. config.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password) ;
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db =mysqli_select_db($conn,"test");
?>
2. function.php
<?php
include('config.php');
function addRecord($table,$columns,$val){
$insertQuery = "INSERT INTO ".$table." ($columns) VALUES('".$val."')";
return $insertQuery;
}
?>
3. emp.php
Hear i called addRecord function from function.php file for add record into database.
<?php
include('config.php');
include('function.php');
$columns= array('employee_name','employee_salary','employee_age');
$values =array('Jack','12000','15');
$val = "".implode("','", $values)."";
$col = "`".implode("`,`", $columns)."`";
addRecord('employee',$col,$val);
It's given me warning because of i passed NULL in $values array so during add record it's display Warning: Missing argument
Note: id is auto increment in DB
When i print query it's showing
INSERT INTO employee VALUES('Jack','12000','15');
And i used same query in mysql it's given error
#1136 - Column count doesn't match value count at row 1
Someone please help me where i need to change in my code.

Your functions are slightly off.
function addRecord($table,$coloumn,$values){
$insertQuery = "INSERT INTO ".$table." VALUES('".$values."')";
}
This does not return anything, also, the variable $coloumn is never used.
I cannot see where your actual mysql insert is happening, but as that function doesn't do anything except assign a string to a variable, it cannot do anything.
It's given me warning because of i passed NULL in $values array so during add record it's display
You are calling this function as addRecord('employee',$val);, and as you can see, you are passing $val where $coloumn should be, remove $coloumn from the function, and that warning will go away
Also
$columns= array('id','employee_name','employee_salary','employee_age');
$values =array(NULL,'Jack','12000','15');
should be
$columns= array('employee_name','employee_salary','employee_age');
$values =array('Jack','12000','15');
Then:
function addRecord($table,$values){
return "INSERT INTO ".$table." VALUES('".$values."')";
}
$addQuery = addRecord('employee',$val);
and use $addQuery in your statement.
1136 - Column count doesn't match value count at row 1
This is because you are not specifying which columns to insert, and MySQL knows that there are 4 columns, including the ID, and you are giving it three values.
Your query should be:
INSERT INTO employee (employee_name, employee_salary, employee_age) VALUES('Jack','12000','15');

Change :
$columns= array('id','employee_name','employee_salary','employee_age');
$values =array(NULL,'Jack','12000','15');
to
$columns= array('employee_name','employee_salary','employee_age');
$values =array('Jack','12000','15');

Related

How can I avoid inserting empty rows into MySQL when working with PHP variables that have no value?

I have searched for the last few hours on this and have come up empty.
I am using a sample piece of code that I have edited slightly to work as needed. It posts values to a MySQL table, each set to a respective row. What I would like to be able to do is have the code not create a row if the PHP variable does not have a value. I am still relatively new with MySQL but have been really digging in so please if you have an answer, help me understand some of the meaning behind it. Thank you for your help!
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$col1Val1 = $_POST['col1Val1'];
$col1Val2 = $_POST['col1Val2'];
$col1Val3 = $_POST['col1Val3'];
$col2Val1 = $_POST['col2Val1'];
$col2Val2 = $_POST['col2Val2'];
$col2Val3 = $_POST['col2Val3'];
$col3Val1 = $_POST['col3Val1'];
$col3Val2 = $_POST['col3Val2'];
$col3Val3 = $_POST['col3Val3'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// begin the transaction
$conn->beginTransaction();
// our SQL statements
$conn->exec("INSERT INTO tableName(column1, column2, column3)
VALUES ('$col1Val1', '$col2Val1', '$col3Val1'),
('$col1Val2', '$col2Val2', '$col3Val2'),
('$col1Val3', '$col2Val3', '$col3Val3')");
// commit the transaction
$conn->commit();
echo "New records created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
The way that query is currently written with multiple value sets, it's going to insert three rows whether they're empty or not. You need to evaluate each row separately in order to avoid inserting empty ones.
You have two main options.
Prepare an INSERT statement with placeholders for one row of values, iterate your $_POST and only execute the statement with rows that aren't empty. This is what I would suggest. With only a maximum of three rows to insert, the performance hit of executing multiple queries should be minimal.
Build your INSERT statement dynamically, and append a set of values for each of the rows that aren't empty. This is fine too, and it is still possible to construct a prepared statement that way, but for something like this it seems more complicated than necessary.
My suggestion for option 1:
$sql = "INSERT INTO tableName(column1, column2, column3) VALUES (?, ?, ?)";
$statement = $conn->prepare($sql);
for ($i=1; $i <= 3; $i++) {
$row = [];
for ($j=0; $j <= 3; $j++) {
$row[] = $_POST["col{$i}Val{$j}"];
}
if (array_filter($row)) { // check if the row has any non-empty values
$statement->execute($row);
}
}
This could be simplified a bit if you changed the names of your form fields up a bit so that you could get the values from sub-arrays in $_POST.
So thank you to all who gave me some tips. I believe I came up with a solution that will work decently for anyone who comes across the same issue.
What I did was for each set of data that goes to its own row, I created an ID field "row#Data" in the HTML that is defaulted to 0 but changes to 1 if each value is filled out. Then I used the if statement for each row instead of checking each variable.
There may be other ways to do this dynamically but to ensure functionality, this is what I came up with.
if ($row1Data == 1) $conn->exec(INSERT INTO...
if ($row2Data == 1) $conn->exec(INSERT INTO...
if ($row3Data == 1) $conn->exec(INSERT INTO...
...

can't echo out an int variable

I've tried to use the solutions presented in this question,
to no avail, so I used this:
$stat = "SELECT MAX(employee_id) FROM employees";
$querysult = intval($connection, $stat);
Where employee_id is an int(3) in the database table.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight. But my question is about what I did immediately after, which was
echo "Id: " . $querysult;
and which output nothing but
Id:
and no number. I've also tried casting the number to a string, and concatenating it to an empty string before the echo statement.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight
This of course is quite impossible, unless you are getting something from a previously executed query that uses the same variable names.
I think your main problem is that accessing the value of the query coded using just SELECT MAX(employee_id) will return a column with the name MAX(employee_id) and that is not a valid PHP variable name. So what you have to do is give that column another name that is a valid PHP variables name using this syntax SELECT MAX(employee_id) as max_empid which renames the column to max_empid
I am assuming nothing so I will also include a connection to the database in my answer. You will need to replace the my_user, my_password and my_db values, or ignore the connection if you have already dont that somewhere else. I have also used the Object Oriented approach to MYSQLI, if you are using the proceedural calls, you may have to amend the code accordingly
// connect to your database
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
// build query and use an alias for the `MAX(employee_id)`
// so you can easily use its name in the result set
$sql = "SELECT MAX(employee_id) as max_empid FROM employees";
// Now we must execute this query
$result = $mysqli->query($sql);
// Now we must chech that the query worked
if ( $result === FALSE ) {
echo sprintf( 'Query Failed: %s<br>%s', $sql, $mysqli->error);
exit;
}
// now we must read one of the rows from the result set
// produced by the ->query() command.
// In this case there of course there is only one result row
$row = $result->fetch_object();
echo 'Id: ' . $row->max_empid;
It may be because you are trying to convert a connection to an int value.
Try this
$connection = new mysqli();
$querysult =mysqli_query( $stat);
printf("Select returned %d.\n", $querysult->num_rows);

How to store an array into a table?

I'm trying to store an array into a table but its not working it adds the table but it doesn't add the column name at all. It's just empty
Here's the entire code.
<?php
include 'db.php';
if(isset($_GET['NAME'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
mysql_query("INSERT INTO $sector (Name) VALUES ('$name') ") or die(mysql_error()) ;
}
if(isset($_GET['TYPE'])) {
file_put_contents('contents.txt', $_GET['TYPE'] . "\n", FILE_APPEND);
}
if(isset($_GET['ISEXPLORED'])) {
file_put_contents('contents.txt', $_GET['ISEXPLORED'] . "\n", FILE_APPEND);
}
if(isset($_GET['SECTORPOSITION'])) {
mysql_query("CREATE TABLE `".$_GET['SECTORPOSITION']."` ( Name VARCHAR(30), Type VARCHAR(30), IsExplored VARCHAR(30), SectorPosition VARCHAR(30), guid VARCHAR(30))");
}
if(isset($_GET['GUID'])) {
file_put_contents('contents.txt', $_GET['GUID'] . "\n", FILE_APPEND);
}
print('Added!');
?>
'RESOLVED THANKS TO ECHO'
'move the code of creating table first then insert to that table. you are inserting then creating table , you should do the opposite.'
Problem 2
Hey guys. I'm having an issue when I do
/test/test.php?SECTORPOSITION=13137&NAME=hibb&TYPE=Cluster&ISEXPLORED=true&GUID=13 I get a syntax error.
But when I do
?SECTORPOSITION=hey&NAME=hibb&TYPE=Cluster&ISEXPLORED=true&GUID=13 It works fine?
Here's my code.
<?php
include 'db.php';
if(isset($_GET['SECTORPOSITION'])) {
mysql_query("CREATE TABLE `".$_GET['SECTORPOSITION']."` ( Name INT, Type VARCHAR(30), IsExplored VARCHAR(30), SectorPosition INT, guid INT)");
}
if(isset($_GET['TYPE'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$type= mysql_real_escape_string($_GET['TYPE']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
$isexplored = mysql_real_escape_string($_GET['ISEXPLORED']) ; // escape your variable here
$guid = mysql_real_escape_string($_GET['GUID']) ; // escape your variable here
mysql_query("INSERT INTO $sector (Name,Type,IsExplored,SectorPosition,guid) VALUES ('$name','$type','$isexplored','$sector','$guid') ") or die(mysql_error()) ;
}
print('Added!');
?>
you can do like this
look like I have an array
$array = array(1,2,3,4);
json_encode($array);
and save the json encoded value
Its not standard to store array in db. You could see any cms, they would store it as json encoded objects, so that they can retrieve back the values
Dont use mysql_ functions anymore (its a sin!), use the improved. Use mysqli_. Like this:
$con = new mysqli('localhost', 'username', 'password', 'database');
if(isset($_GET['NAME'])) {
$your_table_whitelist = array('table1', 'table2'); // list your tables
if(!in_array($_GET['SECTORPOSITION'], $your_table_whitelist, true)) {
exit; // no table like that found
}
$stmt = $con->prepare("INSERT INTO {$_GET['SECTORPOSITION']} (Name) VALUES(?)");
$stmt->bind_param('s', $_GET['NAME']);
$stmt->execute();
}
Things to point out:
your current code is open to SQL injections, use MYSQLI and utilize parameterized queries instead.
since you cannot bind tables inside, just create a whitelist of table to compare to your variable which will hold the table name. If it matches, its okay, it's not, just handle that error.
your code is very open to sql injection you should go to mysqli or pdo.
if(isset($_GET['NAME'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
mysql_query("INSERT INTO $sector (Name) VALUES ('$name') ") or die(mysql_error()) ;
}
EDIT: you got this error
Table 'TheGalaxy.at' doesn't exist
because you are creating table after the insert , so the table is not created yet.
Please do not use mysql function as they're deprecated, instead use mysqli.
the proper way to insert data into the database as follows :
mysqli_query($link, "INSERT INTO tableName values('".$_GET['NAME']."')");
where $link is your connection string. like
$link = ("myhost","myUser","myPassword","myDB");
Hope this will help.
if(isset($_GET['NAME'])) {
$sql= "INSERT INTO ".$_GET['SECTORPOSITION']."(name) VALUES(".$_GET['NAME'].")";
mysql_query($sql);
}

Querying database with php

I am trying to query my database using php, to then display the results of the query. For this example, I only want the number of elements in my MySQL database.
My code is:
<?php
print("This is just a test");
print("This is another test");
// Create connection
$con=mysqli_connect("mysql.netsons.com","****","****","****");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
print("A third test");
$result = mysqli_query($con, "SELECT COUNT(*) FROM MyGames");
echo $result;
echo mysqli_fetch_array($result);
print("A forth test");
mysqli_close($con);
?>
This is the result:
This is just a testThis is another testA third test
What am I doing wrong?
mysql_fetch_array fetches ... an array.
$row = mysqli_fetch_array($result);
echo $row["COUNT(*)"];
I think it would be better to alias that column too:
SELECT COUNT(*) AS count FROM MyGames
...
echo $row['count'];
I would recomend using a diferent method of querying that is much safer(As far as I know there is no SQL Injection to worry about) and it saves a lot of time and space.
First you need to create an mysqli object
$stateConnect = new mysqli("localhost", "root", "PASS", "DBTable");
This does the same thing as mysqli_connect and mysqli_select_db
Then you want to define your SQL query
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=?";
Next you want to create a variable called a statement with your SQL "attached to it"
$statement = $stateConnect->prepare($sql);
Notice how in my SQL I didn't directly put the value required for userEmail, instead I put an '?'. This acts as a variable that we will later define(However it will always be a '?'
To define this variable we need to use.
$statement->bind_param('s', $SESSION['email']);
This binds $SESSION['email'] to the first qustion mark, the s is saying that the first question mark will be a string. Lets say we had to varribles:
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=? AND `userName`=?";
We would then use:
$statement->bind_param('ss', $SESSION['email'], "USERNAME");
Each s replresents a question mark and each value after that represents a question mark.
Now we have to execute our query with.
$statement->execute();
If we are expecting a result to be returned then we have to use
$statement->bind_result($userVotesText);
To bind the results to a variable, If I was expecting to columns of results I would need to put a second variable in.
Now to set those varribles we need to use
if($statement->fetch()){
$userVotesResult = userVotesText;
}
This method is much better than other for querying databases and is called Prepared Statement

mssql pdo If Exists insert prepared statement in a loop

I have a prepared statement which is designed to insert row if a row didn't previously exist. If only one row is to be done it works fine. If there's two, the first row is added and the second ignored. If the first row exists and the second doesn't, the second is added and all following rows fail.
Effectively the insert works once and it's as if the IF NOT EXISTS doesn't update the binding of the new parameters.
Here is the sample code:
$dbConn = 'mssql:host=' . $server . ';dbname=' . $base;
$dbh = new PDO( $dbConn, $user, $pass);
// Go through each course code and add it
// Ignore if it already exists
$stmt = $dbh->prepare('IF NOT EXISTS (SELECT * FROM _ExamCoursesTEMP
WHERE ExamCourseCode = :examCode AND CourseCode = :courseCode )
BEGIN
INSERT INTO _ExamCoursesTEMP ( ExamCourseCode, CourseCode ) VALUES ( :examCode2, :courseCode2 )
END');
$counter = 0;
foreach( $courseCodes as $courseCode )
{
$stmt->bindParam(':examCode', $examCode );
$stmt->bindParam(':courseCode', $courseCode );
$stmt->bindParam(':examCode2', $examCode );
$stmt->bindParam(':courseCode2', $courseCode );
$updateCount = $stmt->execute();
$counter++;
}
The first updateCount returns 1 and all the rest are empty.
I'm not sure if this is an issue with my code, the prepared statement bindings though PDO or a quirk of mssql.
Any help would be appreciated.
Thanks.
The second parameter to bindParam is passed by reference. Thus, it is only necessary to bind the parameter to the variable once, then change the value assigned to that same variable in your loop.

Categories