Mysqli insert error

PHP MySQL Insert Data Insert Data Into MySQL Using MySQLi and PDO After a database and a table have been created, we can start adding data in them. Here are some syntax rules to follow: The SQL query must be quoted in PHP String values inside the SQL query must be quoted Numeric values […]

Содержание

  1. PHP MySQL Insert Data
  2. Insert Data Into MySQL Using MySQLi and PDO
  3. Example (MySQLi Object-oriented)
  4. mysqli::$error
  5. Description
  6. Parameters
  7. Return Values
  8. Examples
  9. See Also
  10. User Contributed Notes 7 notes
  11. PHP5 MySQL Вставить данные
  12. MySQL Вставьте данные, используя mysqli и PDO
  13. Пример MySQLi — объектно-ориентированный
  14. Пример MySQLi — процессуальный
  15. Пример PDO
  16. PHP5 MySQL Вставить данные
  17. MySQL Вставьте данные, используя mysqli и PDO
  18. Пример MySQLi — объектно-ориентированный
  19. Пример MySQLi — процессуальный
  20. Пример PDO
  21. mysql_error
  22. Description
  23. Parameters
  24. Return Values
  25. Examples
  26. See Also
  27. User Contributed Notes 14 notes

PHP MySQL Insert Data

Insert Data Into MySQL Using MySQLi and PDO

After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

  • The SQL query must be quoted in PHP
  • String values inside the SQL query must be quoted
  • Numeric values must not be quoted
  • The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

To learn more about SQL, please visit our SQL tutorial.

In the previous chapter we created an empty table named «MyGuests» with five columns: «id», «firstname», «lastname», «email» and «reg_date». Now, let us fill the table with data.

Note: If a column is AUTO_INCREMENT (like the «id» column) or TIMESTAMP with default update of current_timesamp (like the «reg_date» column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

The following examples add a new record to the «MyGuests» table:

Example (MySQLi Object-oriented)

connect_error) <
die(«Connection failed: » . $conn->connect_error);
>

$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘John’, ‘Doe’, ‘john@example.com’)»;

if ($conn->query($sql) === TRUE) <
echo «New record created successfully»;
> else <
echo «Error: » . $sql . «
» . $conn->error;
>

Источник

mysqli::$error

(PHP 5, PHP 7, PHP 8)

mysqli::$error — mysqli_error — Returns a string description of the last error

Description

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

Parameters

Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

Return Values

A string that describes the error. An empty string if no error occurred.

Examples

Example #1 $mysqli->error example

= new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

/* check connection */
if ( $mysqli -> connect_errno ) <
printf ( «Connect failed: %sn» , $mysqli -> connect_error );
exit();
>

if (! $mysqli -> query ( «SET a=1» )) <
printf ( «Error message: %sn» , $mysqli -> error );
>

/* close connection */
$mysqli -> close ();
?>

= mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

/* check connection */
if ( mysqli_connect_errno ()) <
printf ( «Connect failed: %sn» , mysqli_connect_error ());
exit();
>

if (! mysqli_query ( $link , «SET a=1» )) <
printf ( «Error message: %sn» , mysqli_error ( $link ));
>

/* close connection */
mysqli_close ( $link );
?>

The above examples will output:

See Also

  • mysqli_connect_errno() — Returns the error code from last connect call
  • mysqli_connect_error() — Returns a description of the last connection error
  • mysqli_errno() — Returns the error code for the most recent function call
  • mysqli_sqlstate() — Returns the SQLSTATE error from previous MySQL operation

User Contributed Notes 7 notes

The mysqli_sql_exception class is not available to PHP 5.05

I used this code to catch errors
= «SELECT XXname FROM customer_table » ;
$res = $mysqli -> query ( $query );

if (! $res ) <
printf ( «Errormessage: %sn» , $mysqli -> error );
>

?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn’t tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.

So, a better way is:
= «SELECT XXname FROM customer_table » ;
$res = $mysqli -> query ( $query );

if (! $mysqli -> error ) <
printf ( «Errormessage: %sn» , $mysqli -> error );
>

?>

This would output something like:
Unexpected PHP error [mysqli::query() [function.query]: (42S22/1054): Unknown column ‘XXname’ in ‘field list’] severity [E_WARNING] in [G:database.php] line [249]

Very frustrating as I wanted to also catch the sql error and print out the stack trace.

A better way is:

( MYSQLI_REPORT_OFF ); //Turn off irritating default messages

$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

$query = «SELECT XXname FROM customer_table » ;
$res = $mysqli -> query ( $query );

if ( $mysqli -> error ) <
try <
throw new Exception ( «MySQL error $mysqli -> error
Query:
$query » , $msqli -> errno );
> catch( Exception $e ) <
echo «Error No: » . $e -> getCode (). » — » . $e -> getMessage () . «
» ;
echo nl2br ( $e -> getTraceAsString ());
>
>

//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column ‘XXname’ in ‘field list’
Query:
SELECT XXname FROM customer_table

#0 G:\database.php(251): database->dbError(‘Unknown column . ‘, 1054, ‘getQuery()’, ‘SELECT XXname F. ‘)
#1 G:dataWorkSites1framework5testsdbtest.php(29): database->getString(‘SELECT XXname F. ‘)
#2 c:PHPincludessimpletestrunner.php(58): testOfDB->testGetVal()
#3 c:PHPincludessimpletestrunner.php(96): SimpleInvoker->invoke(‘testGetVal’)
#4 c:PHPincludessimpletestrunner.php(125): SimpleInvokerDecorator->invoke(‘testGetVal’)
#5 c:PHPincludessimpletestrunner.php(183): SimpleErrorTrappingInvoker->invoke(‘testGetVal’)
#6 c:PHPincludessimpletestsimple_test.php(90): SimpleRunner->run()
#7 c:PHPincludessimpletestsimple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:PHPincludessimpletestsimple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:all_tests.php(16): GroupTest->run(Object(HtmlReporter))

This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.

The decription «mysqli_error — Returns a string description of the LAST error» is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.

If you have the following situation

if (!$mysqli->query(«SET a=1»)) <
$mysqli->query(«ROLLBACK;»)
printf(«Errormessage: %sn», $mysqli->error);
>

you don’t get an error-message, if the ROLLBACK-Query didn’t failed, too. In order to get the right error-message you have to write:

if (!$mysqli->query(«SET a=1»)) <
printf(«Errormessage: %sn», $mysqli->error);
$mysqli->query(«ROLLBACK;»)
>

I had to set mysqli_report(MYSQLI_REPORT_ALL) at the begin of my script to be able to catch mysqli errors within the catch block of my php code.

Initially, I used the below code to throw and subsequent catch mysqli exceptions

try <
$mysqli = new mysqli ( ‘localhost’ , ‘root’ , ‘pwd’ , ‘db’ );
if ( $mysqli -> connect_errno )
throw new Exception ( $mysqli -> connect_error );

> catch ( Exception $e ) <
echo $e -> getMessage ();
>

I realized the exception was being thrown before the actual throw statement and hence the catch block was not being called .

My current code looks like
mysqli_report ( MYSQLI_REPORT_ALL ) ;
try <
$mysqli = new mysqli ( ‘localhost’ , ‘root’ , ‘pwd’ , ‘db’ );
/* I don’t need to throw the exception, it’s being thrown automatically */

> catch ( Exception $e ) <
echo $e -> getMessage ();
>

This works fine and I ‘m able to trap all mysqli errors

// The idea is the add formated errors information for developers to easier bugs detection.

$myfile = fopen ( «database_log.log» , «r» );
$db = new mysqli ( «localhost» , «root» , «root» , «data» );
if(! $db -> query ( «SELECT» )) <
$timestamp = new DateTime ();
$data_err = » <
»title»: » Select statement error »,
»date_time»: » . $timestamp -> getTimestamp (). «,
»error»:» » . $db -> error . » »
> » ; // Do more information
fwrite ( $myfile , $data_err ); // writing data
>
// In separate file do file read and format it for good visual.

$db -> close ();
fclose ( $myfile );
?>

Please note that the string returned may contain data initially provided by the user, possibly making your code vulnerable to XSS.

So even if you escape everything in your SQL query using mysqli_real_escape_string(), make sure that if you plan to display the string returned by mysqli_error() you run that string through htmlspecialchars().

As far as I can tell the two escape functions don’t escape the same characters, which is why you need both (the first for SQL and the second for HTML/JS).

Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
//set up $mysqli_instance here..
$Select = «SELECT xyz FROM mytable » ;
try <
$res = $mysqli_instance -> query ( $Select );
>catch ( mysqli_sql_exception $e ) <
print «Error Code
» . $e -> getCode ();
print «Error Message
» . $e -> getMessage ();
print «Strack Trace
» . nl2br ( $e -> getTraceAsString ());
>

Источник

PHP5 MySQL Вставить данные

MySQL Вставьте данные, используя mysqli и PDO

После создания базы данных и таблицы мы можем начать добавлять данные.

Ниже приведены некоторые синтаксические правила:

  • SQL запрос должен быть заключен в кавычки
  • Строковых значений в SQL запросе должны быть заключены в кавычки
  • Цифровые значения не должны заключатся в кавычки
  • Слово NULL не должено заключатся в кавычки

Заявление INSERT INTO используется, чтобы добавить новые записи к таблице MySQL:

Чтобы узнать больше о SQL, пожалуйста, посетите наш Учебник SQL.

В предыдущей главе, мы создали пустую таблицу с именем «MyGuests» , с пятью столбиками: «id» , «firstname» , «lastname» , «email» и «reg_date» . Теперь давайте заполним таблицу данными.

Примечание: AUTO_INCREMENT ( «id» столбец) или TIMESTAMP ( «reg_date» столбец), не нужно указывать в SQL запросе; MySQL автоматически добавит заявление.

Следующие примеры добавляют новую запись в таблицу «MyGuests» :

Пример MySQLi — объектно-ориентированный

connect_error) <
die(«Ошибка подключения: » . $conn->connect_error);
>

// Установка данных в таблицу
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Андрей’, ‘Щипунов’, ‘and-shhipunov@mail.ru’)»;

if ($conn->query($sql) === TRUE) <
echo «Успешно создана новая запись»;
> else <
echo «Ошибка: » . $sql . «
» . $conn->error;
>

// Закрыть подключение
$conn->close();
?>

Пример MySQLi — процессуальный

Пример PDO

// Установка данных в таблицу
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Андрей’, ‘Щипунов’, ‘and-shhipunov@mail.ru’)»;

// Используйте exec (), поскольку результаты не возвращаются
$conn->exec($sql);
echo «Успешно создана новая запись»;
>
catch(PDOException $e)
<
echo $sql . «
» . $e->getMessage();
>

// Закрыть подключение
$conn = null;
?>

Источник

PHP5 MySQL Вставить данные

MySQL Вставьте данные, используя mysqli и PDO

После создания базы данных и таблицы мы можем начать добавлять данные.

Ниже приведены некоторые синтаксические правила:

  • SQL запрос должен быть заключен в кавычки
  • Строковых значений в SQL запросе должны быть заключены в кавычки
  • Цифровые значения не должны заключатся в кавычки
  • Слово NULL не должено заключатся в кавычки

Заявление INSERT INTO используется, чтобы добавить новые записи к таблице MySQL:

Чтобы узнать больше о SQL, пожалуйста, посетите наш Учебник SQL.

В предыдущей главе, мы создали пустую таблицу с именем «MyGuests» , с пятью столбиками: «id» , «firstname» , «lastname» , «email» и «reg_date» . Теперь давайте заполним таблицу данными.

Примечание: AUTO_INCREMENT ( «id» столбец) или TIMESTAMP ( «reg_date» столбец), не нужно указывать в SQL запросе; MySQL автоматически добавит заявление.

Следующие примеры добавляют новую запись в таблицу «MyGuests» :

Пример MySQLi — объектно-ориентированный

connect_error) <
die(«Ошибка подключения: » . $conn->connect_error);
>

// Установка данных в таблицу
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Андрей’, ‘Щипунов’, ‘and-shhipunov@mail.ru’)»;

if ($conn->query($sql) === TRUE) <
echo «Успешно создана новая запись»;
> else <
echo «Ошибка: » . $sql . «
» . $conn->error;
>

// Закрыть подключение
$conn->close();
?>

Пример MySQLi — процессуальный

Пример PDO

// Установка данных в таблицу
$sql = «INSERT INTO MyGuests (firstname, lastname, email)
VALUES (‘Андрей’, ‘Щипунов’, ‘and-shhipunov@mail.ru’)»;

// Используйте exec (), поскольку результаты не возвращаются
$conn->exec($sql);
echo «Успешно создана новая запись»;
>
catch(PDOException $e)
<
echo $sql . «
» . $e->getMessage();
>

// Закрыть подключение
$conn = null;
?>

Источник

mysql_error

mysql_error — Returns the text of the error message from previous MySQL operation

This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide. Alternatives to this function include:

Description

Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno() ), so if you want to use it, make sure you check the value before calling another MySQL function.

Parameters

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

Return Values

Returns the error text from the last MySQL function, or » (empty string) if no error occurred.

Examples

Example #1 mysql_error() example

= mysql_connect ( «localhost» , «mysql_user» , «mysql_password» );

mysql_select_db ( «nonexistentdb» , $link );
echo mysql_errno ( $link ) . «: » . mysql_error ( $link ). «n» ;

mysql_select_db ( «kossu» , $link );
mysql_query ( «SELECT * FROM nonexistenttable» , $link );
echo mysql_errno ( $link ) . «: » . mysql_error ( $link ) . «n» ;
?>

The above example will output something similar to:

See Also

  • mysql_errno() — Returns the numerical value of the error message from previous MySQL operation
  • » MySQL error codes

User Contributed Notes 14 notes

If you want to display errors like «Access denied. «, when mysql_error() returns «» and mysql_errno() returns 0, use $php_errormsg. This Warning will be stored there. You need to have track_errors set to true in your php.ini.

Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says: «Errors coming back from the MySQL database backend no longer issue warnings.» Which is not true.

Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.

Just spent a good 30 minutes trying to figure out why i didn’t see my SQL errors.

Using a manipulation of josh ><>‘s function, I created the following. It’s purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman’s escape_data() as well since I use it in q().

function escape_data ( $data ) <
global $dbc ;
if( ini_get ( ‘magic_quotes_gpc’ )) <
$data = stripslashes ( $data );
>
return mysql_real_escape_string ( trim ( $data ), $dbc );
>

function q ( $page , $query ) <
// $page
$result = mysql_query ( $query );
if ( mysql_errno ()) <
$error = «MySQL error » . mysql_errno (). «: » . mysql_error (). «n
When executing:
n $query n
» ;
$log = mysql_query ( «INSERT INTO db_errors (error_page,error_text) VALUES (‘ $page ‘,’» . escape_data ( $error ). «‘)» );
>
>

// Run the query using q()
$query = «INSERT INTO names (first, last) VALUES (‘myfirst’, ‘mylast’» );
$result = q ( «Sample Page Title» , $query );
?>

When creating large applications it’s quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.

This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.

The script writes a log file in directory ( in this case /log ) as well.

The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.

$system_operator_mail = ‘developer@company.com’ ;
$system_from_mail = ‘info@mywebsite.com’ ;

function db_query ( $query ) <
global $b_debugmode ;

// Perform Query
$result = mysql_query ( $query );

// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (! $result ) <
if( $b_debugmode ) <
$message = ‘Invalid query:
‘ . mysql_error () . ‘

raise_error ( ‘db_query_error: ‘ . $message );
>
return $result ;
>

function raise_error ( $message ) <
global $system_operator_mail , $system_from_mail ;

$serror =
«Env: » . $_SERVER [ ‘SERVER_NAME’ ] . «rn» .
«timestamp: » . Date ( ‘m/d/Y H:i:s’ ) . «rn» .
«script: » . $_SERVER [ ‘PHP_SELF’ ] . «rn» .
«error: » . $message . «rnrn» ;

// open a log file and write error
$fhandle = fopen ( ‘/logs/errors’ . date ( ‘Ymd’ ). ‘.txt’ , ‘a’ );
if( $fhandle ) <
fwrite ( $fhandle , $serror );
fclose (( $fhandle ));
>

// e-mail error to system operator
if(! $b_debugmode )
mail ( $system_operator_mail , ‘error: ‘ . $message , $serror , ‘From: ‘ . $system_from_mail );
>

My suggested implementation of mysql_error():

$result = mysql_query($query) or die(«A fatal MySQL error occured.n
Query: » . $query . «
nError: (» . mysql_errno() . «) » . mysql_error());

This will print out something like.

A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It’s very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn’t let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

When dealing with user input, make sure that you use
echo htmlspecialchars ( mysql_error ());
?>
instead of
echo mysql_error ();
?>

Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.

Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?

some error can’t handle. Example:

ERROR 1044: Access denied for user: ‘ituser@mail.ramon.intranet’ to database ‘itcom’

This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = «» .

«Errors coming back from the MySQL database backend no longer issue warnings.» Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host ‘locallllllhost’ (11001)

That’s a warning, which is not trapped by mysql_error()!

My suggested implementation of mysql_error():

$result = mysql_query($query) or die(«A fatal MySQL error occured.n
Query: » . $query . «
nError: (» . mysql_errno() . «) » . mysql_error());

This will print out something like.

A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It’s very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn’t let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Oops, the code in my previous post only works for queries that don’t return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):

function myquery ($query) <
$result = mysql_query($query);
if (mysql_errno())
echo «MySQL error «.mysql_errno().»: «.mysql_error().»n
When executing:
n$queryn
«;
return $result;
>

This is a big one — As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I’m still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():

MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client

According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:

Set PASSWORD for ‘user’@’host’ = OLD_PASSWORD(‘password’);

Источник

Answer by Malani Figueroa

To be honest, I am relatively new at using PHP as well as MySQL, but I can’t seem to find the error in my syntax; the Queued table does exist, $role and $sname are both strings so I encased them in single quotes. I suspect this is a newbie mistake, could anyone point me in the right direction?,Error: INSERT INTO Queued (‘Tops’) VALUES (‘Summoner’)
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near »Tops’) VALUES (‘Summoner’)’ at line 1,

Stack Overflow for Teams
Where developers & technologists share private knowledge with coworkers

,`s role is to differentiate between built in SQL words and the column names, so if a word is used for name of a column that might be also a built in sql expression then « are needed around it

This is due to use of single quotes ' around the column name. The query should be like:

$sql = "INSERT INTO Queued ($role) VALUES ('$sname')";

OR

$sql = "INSERT INTO Queued (`$role`) VALUES ('$sname')";

Answer by Celeste Brown

replace all variables in the query with with question marks (called placeholders or parameters),create a correct SQL INSERT statement,Like it was said above, first we are writing an SQL query where all variables are substituted with question marks. ,IMPORTANT! there should be no quotes around question marks, you are adding placeholders, not strings.

Just write a code like in this example

$sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";$stmt= $conn->prepare($sql);$stmt->bind_param("sss", $name, $email, $password);$stmt->execute();

What is going on here?

$sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";

IMPORTANT! there should be no quotes around question marks, you are adding placeholders, not strings.

$stmt= $conn->prepare($sql);

Then, the query is prepared. The idea is very smart. To avoid even a possibility of the SQL injection or a syntax error caused by the input data, the query and the data are sent to database server separately. So it goes on here: with prepare() we are sending the query to database server ahead. A special variable, a statement is created as a result. We would use this variable from now on.

$stmt->bind_param("sss", $name, $email, $passwor);

So you can tell now that «sss» means «there would be 3 variables, all of string type». And then, naturally, three variables obediently follow.

$stmt->execute();

As you may noted, the code is quite verbose. If you like to build a code like a Lego figure, with shining ranks of operators, you may keep it as is. If you, like me, hate useless repetitions and like to write concise and meaningful code, then there is a simple helper function. With it, the code will become two times shorter:

$sql = "INSERT INTO users (name, email, password) VALUES (?,?,?)";prepared_query($conn, $sql, [$name, $email, $password]);

First of all this function will need a helper function of its own. We will need a function to escape MySQL identifiers. Yes, all identifiers must be quoted and escaped, according to MySQL standards, in order to avoid various syntax issues.

function escape_mysql_identifier($field){    return "`".str_replace("`", "``", $field)."`";}

And now we can finally have a function that accepts a table name and an array with data and runs a prepared INSERT query against a database:

function prepared_insert($conn, $table, $data) {    $keys = array_keys($data);    $keys = array_map('escape_mysql_identifier', $keys);    $fields = implode(",", $keys);    $table = escape_mysql_identifier($table);    $placeholders = str_repeat('?,', count($keys) - 1) . '?';    $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";    prepared_query($conn, $sql, array_values($data));}

Answer by Dream Lamb

This is how your code should look (with added SQL Injection protection):,According to the mysqli_query documentation, the first parameter must be a connection string:,This way, you can always be sure that not a single SQL syntax error can be caused by the data you added to the query! As a bonus, this code is bullet-proof against SQL injection too!,yo need create the user «pma» in mysql or change this lines(user and password for mysql):

I know a lot of people have the same error occasionally however I have looked at all previous answers and my code and i have tried col with and without backticks
Here is my current code
I also have tried with $var as well as just $var but same

if(!empty($_POST['email'])){
 $date = date('dmY'); #Todays Date
 $ip = str_replace('.','',$_SERVER['REMOTE_ADDR']); #Visitor IP
 $verify = md5($date.$ip); #MD5 ENCRYPT THE 2 VALUES
 $fname = $_POST['fname'];
 $lname = $_POST['lname'];  
 $email = $_POST['email'];
 $password = md5($_POST['password']);
 $link = mysqli_connect($dbh,$dbu, $dbp, $dbn);

 $query = mysqli_query($link, "INSERT INTO `users` (`email`,`fname`,`lname`,`verify`,`password`,`joined`)
VALUES($email,$fname,$lname,$verify,$password,$date)");

 if($query){ 
  echo "inserted"; 
 }
 else { 
  echo mysqli_error($link);
 }

Answer by Antonella Nava

Returns the last error message for the most recent MySQLi function call
that can succeed or fail.
,Procedural style only: A mysqli object
returned by mysqli_connect() or mysqli_init()
,mysqli_errno() — Returns the error code for the most recent function call,mysqli_connect_errno() — Returns the error code from last connect call

Error message: Unknown system variable 'a'

Answer by Raiden Garrett

Web Development Forum

,

Programming Forum

,https://www.daniweb.com/programming/web-development/tutorials/499320/common-issues-with-mysql-and-php,

error in connection when loged in session for other user

2

My Error info isnt being clear enough for me to understand the problemIs there anything worng here so i can continue on lookng for the probelm:

$sql = "INSERT INTO boards (
    title, genre, creator, tagline, intro, remessage, visability, recruitment, reqsheet, reqdice, reqgroup, ppweek)
    VALUES (
    $title, $genre, $creator, ". $tagline . ", $scene, $message, $vis, $rcrt, $sheet, $dice, $group, $ppw)";

    if ($conn->query($sql) === TRUE) 
    {
        echo "New record created successfully";
    } 
    else 
    {
        echo "<br>Error: " . $sql . "<br>" . $conn->error;
    }

Answer by Omari Lugo

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$mysqli = new mysqli("localhost", "root", "", "demo");
 
// Check connection
if($mysqli === false){
    die("ERROR: Could not connect. " . $mysqli->connect_error);
}
 
// Escape user inputs for security
$first_name = $mysqli->real_escape_string($_REQUEST['first_name']);
$last_name = $mysqli->real_escape_string($_REQUEST['last_name']);
$email = $mysqli->real_escape_string($_REQUEST['email']);
 
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
if($mysqli->query($sql) === true){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
 
// Close connection
$mysqli->close();
?>

Answer by Zion Schroeder

There is a syntax error which, unfortunately, caused our script to fail. The error was here:,We used curly brackets instead of the simple parenthesis. Since this is not correct it caused our script to throw a syntax error.,If a MySQLi error message is displayed we can do the following methods to fix it. For example, let’s make one syntax error in our code, if we do, we will see something similar to this:,All of those errors can be fixed easily by following the error message guidelines or checking the error log.

First, you’ll need to establish a connection to a database. After that is done, we can proceed with the MySQL query INSERT. Here is a full PHP code example with the basic connection and insert methods:

<?php
$servername = "mysql.hostinger.co.uk";
$database = "u266072517_name";
$username = "u266072517_user";
$password = "buystuffpwd";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection

if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
}
 
echo "Connected successfully";
 
$sql = "INSERT INTO Students (name, lastname, email) VALUES ('Test', 'Testing', '[email protected]')";
if (mysqli_query($conn, $sql)) {
      echo "New record created successfully";
} else {
      echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);

?>

So, let’s start with line number 19:

$sql = "INSERT INTO Students (name, lastname, email) VALUES ('Test', 'Testing', '[email protected]')";

The next part of the code (20 – 22 lines) checks if our query was successful:

if (mysqli_query($conn, $sql)) {
     echo "New record created successfully";
}

And the final part (22 – 24 lines) displays a different message in case our query wasn’t successful:

else {
     echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

As with the previous example, we need a connection to the database first which is done by creating a new PDO object – this tutorial will show you how if you are unsure. As the connection to the MySQL database is a PDO object, you must use various PDO methods (any function that is part of any object) to prepare and run queries. Methods of objects are called like this:

$the_Object->the_Method();

PDO allows you to prepare SQL code before it is executed. The SQL query is evaluated and corrected before being run. A simplified SQL injection attack could be done just by typing SQL code into a field on a form. For example:

// User writes this in the username field of a login form
john"; DROP DATABASE user_table;

// The final query becomes this
"SELECT * FROM user_table WHERE username = john"; DROP DATABASE user_table;

On to the correct code:

<?php
$servername = "mysql.hostinger.com";
$database = "u266072517_name"; 
$username = "u266072517_user";
$password = "buystuffpwd";
$sql = "mysql:host=$servername;dbname=$database;";
$dsn_Options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];

// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try { 
  $my_Db_Connection = new PDO($sql, $username, $password, $dsn_Options);
  echo "Connected successfully";
} catch (PDOException $error) {
  echo 'Connection error: ' . $error->getMessage();
}

// Set the variables for the person we want to add to the database
$first_Name = "Test";
$last_Name = "Testing";
$email = "[email protected]";

// Here we create a variable that calls the prepare() method of the database object
// The SQL query you want to run is entered as the parameter, and placeholders are written like this :placeholder_name
$my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO Students (name, lastname, email) VALUES (:first_name, :last_name, :email)");

// Now we tell the script which variable each placeholder actually refers to using the bindParam() method
// First parameter is the placeholder in the statement above - the second parameter is a variable that it should refer to
$my_Insert_Statement->bindParam(:first_name, $first_Name);
$my_Insert_Statement->bindParam(:last_name, $last_Name);
$my_Insert_Statement->bindParam(:email, $email);

// Execute the query using the data we just defined
// The execute() method returns TRUE if it is successful and FALSE if it is not, allowing you to write your own messages here
if ($my_Insert_Statement->execute()) {
  echo "New record created successfully";
} else {
  echo "Unable to create record";
}

// At this point you can change the data of the variables and execute again to add more data to the database
$first_Name = "John";
$last_Name = "Smith";
$email = "[email protected]";
$my_Insert_Statement->execute();

// Execute again now that the variables have changed
if ($my_Insert_Statement->execute()) {
  echo "New record created successfully";
} else {
  echo "Unable to create record";
}

If the query that we ran and insert into MySQL database was successful, we will see the following message like:

Connect Successfully
New record created successfully

If a MySQLi error message is displayed we can do the following methods to fix it. For example, let’s make one syntax error in our code, if we do, we will see something similar to this:

Connect successfully
Error: INSERT INTO students {name, lastname, email} VALUES ('Test', 'Testing', '[email protected]')
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{name, lastname, email} VALUES ('Test', 'Testing', '[email protected]')' at line 1"

As you can see, the first part of the code is good, the connection was established successfully, but our SQL query ran into a wall.

"Error: INSERT INTO Students {name, lastname, email} VALUES ('Thom', 'Vial', '[email protected]') You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{name, lastname, email} VALUES ('Thom', 'Vial', '[email protected]')' at line 1"

There is a syntax error which, unfortunately, caused our script to fail. The error was here:

$sql = "INSERT INTO Students {name, lastname, email} VALUES ('Thom', 'Vial', '[email protected]')";

This should generally only be used when developing a script as it can expose the database and table names, which you may prefer to hide from anyone who might be trying to maliciously access your data. In the case above where curly braces were used instead of parenthesis, the error looks similar to this:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; <code>check the manual that corresponds to your MySQL server version for the right syntax to use near '{name, lastname, email} VALUES ('Thom', 'Vial', '[email protected]')' at line 1"</code>

Answer by Coraline Paul

Write for DigitalOcean
,

DigitalOcean on GitHub

,
Sign in

Sign in to

Community

Control Panel

,
Community Tools and Integrations

This line (from the PastBin above)….

$stmt->execute( array(
            ':field1' => $field1, ':field2' => $field2, ':field3' => $field3, ':field4' => $field4, ':field5' => $field5
) );

is the same as:

$stmt->bindParam( ':field1', $field1 );
$stmt->bindParam( ':field2', $field2 );
$stmt->bindParam( ':field3', $field3);
$stmt->bindParam( ':field4', $field4 );
$stmt->bindParam( ':field5', $field5 );

$stmt->execute();

Answer by Ruby Webster

Here is a generic SQL syntax of INSERT INTO command to insert data into the MySQL table −,To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP.,This example will take three parameters from the user and will insert them into the MySQL table − −,To insert data from the command prompt, we will use SQL INSERT INTO command to insert data into MySQL table tutorials_tbl.

Here is a generic SQL syntax of INSERT INTO command to insert data into the MySQL table −

INSERT INTO table_name ( field1, field2,...fieldN )
   VALUES
   ( value1, value2,...valueN );

The following example will create 3 records into tutorials_tbl table −

[email protected]# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed

mysql> INSERT INTO tutorials_tbl 
   →(tutorial_title, tutorial_author, submission_date)
   →VALUES
   →("Learn PHP", "John Poul", NOW());
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO tutorials_tbl
   →(tutorial_title, tutorial_author, submission_date)
   →VALUES
   →("Learn MySQL", "Abdul S", NOW());
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO tutorials_tbl
   →(tutorial_title, tutorial_author, submission_date)
   →VALUES
   →("JAVA Tutorial", "Sanjay", '2007-05-06');
Query OK, 1 row affected (0.01 sec)
mysql>

Syntax

$mysqli→query($sql,$resultmode)

Access the mysql_example.php deployed on apache web server, enter details and verify the output on submitting the form.

Record inserted successfully.

PHP поддерживает работу с базой данных MySQL. Специальные встроенные функции для работы с MySQL позволяют просто и эффективно работать с этой СУБД: выполнять любые запросы, читать и записывать данные, обрабатывать ошибки.

Сценарий, который подключается к БД, выполняет запрос и показывает результат, будет состоять всего из нескольких строк. Для работы с MySQL не надо ничего дополнительно устанавливать и настраивать; всё необходимое уже доступно вместе со стандартной поставкой PHP.

Что такое mysqli?

mysqli (MySQL Improved) — это расширение PHP, которое добавляет в язык полную поддержку баз данных MySQL. Это расширение поддерживает множество возможностей современных версий MySQL.

Как выглядит работа с базой данных

Типичный процесс работы с СУБД в PHP-сценарии состоит из нескольких шагов:

  1. Установить подключение к серверу СУБД, передав необходимые параметры: адрес, логин, пароль.
  2. Убедиться, что подключение прошло успешно: сервер СУБД доступен, логин и пароль верные и так далее.
  3. Сформировать правильный SQL запрос (например, на чтение данных из таблицы).
  4. Убедиться, что запрос был выполнен успешно.
  5. Получить результат от СУБД в виде массива из записей.
  6. Использовать полученные записи в своём сценарии (например, показать их в виде таблицы).

Функция mysqli connect: соединение с MySQL

Перед началом работы с данными внутри MySQL, нужно открыть соединение с сервером СУБД. В PHP это делается с помощью стандартной функции mysqli_connect(). Функция возвращает результат — ресурс соединения. Данный ресурс используется для всех следующих операций с MySQL.

Но чтобы выполнить соединение с сервером, необходимо знать как минимум три параметра:

  • Адрес сервера СУБД;
  • Логин;
  • Пароль.

Если вы следовали стандартной процедуре установки MySQL или используете OpenServer, то адресом сервера будет localhost, логином — root. При использовании OpenServer пароль для подключения — это пустая строка ‘’, а при самостоятельной установке MySQL пароль вы задавали в одном из шагов мастера установки.

Базовый синтаксис функции mysqli_connect():

mysqli_connect(<адрес сервера>, <имя пользователя>, <пароль>, <имя базы данных>);

Проверка соединения

Первое, что нужно сделать после соединения с СУБД — это выполнить проверку, что оно было успешным. Эта проверка нужна, чтобы исключить ошибку при подключении к БД. Неверные параметры подключения, неправильная настройка или высокая нагрузка заставит MySQL отвергать новые подключения. Все эти ситуации приведут к невозможности соединения, поэтому программист должен проверить успешность подключения к серверу, прежде чем выполнять следующие действия.

Соединение с MySQL устанавливается один раз в сценарии, а затем используется при всех запросах к БД.

Результатом выполнения функции mysqli_connect() будет значение специального типа — ресурс. Если подключение к MySQL не удалось, то функция mysqli_connect() вместо ресурса вернет логическое значение типа «ложь» — false. Хорошей практикой будет всегда проверять результат выполнения этой функции и сравнивать его с ложью.

Соединение с MySQL и проверка на ошибки:

<?php
$link = mysqli_connect("localhost", "root", "");

if ($link == false){
    print("Ошибка: Невозможно подключиться к MySQL " . mysqli_connect_error());
}
else {
    print("Соединение установлено успешно");
}
?>

Функция mysqli_connect_error() просто возвращает текстовое описание последней ошибки MySQL.

Установка кодировки

Первым делом после установки соединения крайне желательно явно задать кодировку, которая будет использоваться при обмене данными с MySQL. Если этого не сделать, то вместо записей со значениями, написанными кириллицей, можно получить последовательность из знаков вопроса: ?????????????????. Вызовите эту функцию сразу после успешной установки соединения: mysqli_set_charset($con, "utf8");

Выполнение запросов

Установив соединение и определив кодировку мы готовы выполнить свои первые SQL-запросы. Вы уже умеете составлять корректные SQL команды и выполнять их через консольный или визуальный интерфейс MySQL-клиента. Те же самые запросы можно отправлять без изменений и из PHP-сценария. Помогут в этом несколько встроенных функций языка.

Два вида запросов

Следует разделять все SQL-запросы на две группы:

  1. Чтение информации (SELECT).
  2. Модификация (UPDATE, INSERT, DELETE).

При выполнении запросов из среды PHP, запросы из второй группы возвращают только результат их исполнения: успех или ошибку.

Запросы первой группы при успешном выполнении возвращают специальный ресурс результата. Его, в свою очередь, можно преобразовать в ассоциативный массив (если нужна одна запись) или в двумерный массив (если требуется список записей).

Добавление записи

Вернёмся к нашему проекту — дневнику наблюдений за погодой. Начнём практическую работу с заполнения таблиц данными. Для начала добавим хотя бы один город в таблицу cities.

Выражение INSERT INTO используется для добавления новых записей в таблицу базы данных.

Составим корректный SQL-запрос на вставку записи с именем города, а затем выполним его путём передачи этого запроса в функцию mysqli_query(), чтобы добавить новые данные в таблицу.

<?php
$link = mysqli_connect("localhost", "root", "");

$sql = 'INSERT INTO cities SET name = "Санкт-Петербург"';
$result = mysqli_query($link, $sql);

if ($result == false) {
    print("Произошла ошибка при выполнении запроса");
}

Обратите внимание, что первым параметром для функции mysqli_query() передаётся ресурс подключения, полученный от функции mysqli_connect(), вторым параметром следует строка с SQL-запросом.

При запросах на изменение данных (не SELECT) результатом выполнения будет логическое значение — true или false, которое будет означать, что запрос выполнить не удалось. Для получения строки с описанием ошибки существует функция mysqli_error($link).

Функция insert id: как получить идентификатор добавленной записи

Следующим шагом будет добавление погодной записи для нового города. Погодные записи хранит таблица weather_log, но, чтобы сослаться на город, необходимо знать идентификатор записи из таблицы cities.

Здесь пригодится функция mysqli_insert_id(). Она принимает единственный аргумент — ресурс соединения, а возвращает идентификатор последней добавленной записи.

Теперь у нас есть всё необходимое, чтобы добавить погодную запись. Вот как будет выглядеть комплексный пример с подключением к MySQL и добавлением двух новых записей:

<?php
$link = mysqli_connect("localhost", "root", "");

if ($link == false){
    print("Ошибка: Невозможно подключиться к MySQL " . mysqli_connect_error());
}
else {
    $sql = 'INSERT INTO cities SET name = "Санкт-Петербург"';
    $result = mysqli_query($link, $sql);

    if ($result == false) {
        print("Произошла ошибка при выполнении запроса");
    }
    else {
        $city_id = mysqli_insert_id($link);

        $sql = 'INSERT INTO weather_log SET city_id = ' . $city_id . ', day = "2017-09-03", temperature = 10, cloud = 1';

        $result = mysqli_query($link, $sql);

        if ($result == false) {
            print("Произошла ошибка при выполнении запроса");
        }
    }
}

Чтение записей

Другая частая операция при работе с базами данных в PHP — это получение записей из таблиц (запросы типа SELECT). Составим SQL-запрос, который будет использовать SELECT выражение. Затем выполним этот запрос с помощью функции mysqli_query(), чтобы получить данные из таблицы.

В этом примере показано, как вывести все существующие города из таблицы cities:

<?php

$sql = 'SELECT id, name FROM cities';

$result = mysqli_query($link, $sql);

while ($row = mysqli_fetch_array($result)) {
    print("Город: " . $row['name'] . "; Идентификатор: . " . $row['id'] . "<br>");
}

В примере выше результат выполнения функции mysqli_query() сохранён в переменной $result. В этой переменной находятся не данные из таблицы, а специальный тип данных — так называемая ссылка на результаты запроса.

Чтобы получить действительные данные, то есть записи из таблицы, следует использовать другую функцию — mysqli_fetch_array() — и передать ей единственным параметром эту самую ссылку. Теперь каждый вызов функции mysqli_fetch_array() будет возвращать следующую запись из всего результирующего набора записей в виде ассоциативного массива.

Цикл while здесь используется для «прохода» по всем записям из полученного набора записей. Значение поля каждой записи можно узнать просто обратившись по ключу этого ассоциативного массива.

Как получить сразу все записи в виде двумерного массива

Иногда бывает удобно после запроса на чтение не вызывать в цикле mysqli_fetch_array для извлечения очередной записи по порядку, а получить их сразу все одним вызовом. PHP так тоже умеет.

Функция mysqli_fetch_all($res, MYSQLI_ASSOC) вернёт двумерный массив со всеми записями из результата последнего запроса. Перепишем пример с показом существующих городов с её использованием:

<?php

$sql = 'SELECT id, name FROM cities';
$result = mysqli_query($link, $sql);

$rows = mysqli_fetch_all($result, MYSQLI_ASSOC)

foreach ($rows as $row) {
    print("Город: " . $row['name'] . "; Идентификатор: . " . $row['id'] . "<br>");
}

Как узнать количество записей

Часто бывает необходимо узнать, сколько всего записей вернёт выполненный SQL запрос. Это может помочь при организации постраничной навигации, или просто в качестве информации. Узнать число записей поможет функция mysqli_num_rows(), которой следует передать ссылку на результат запроса.

За последние 24 часа нас посетили 11353 программиста и 1121 робот. Сейчас ищут 300 программистов …


  1. Пэлт

    С нами с:
    1 апр 2020
    Сообщения:
    103
    Симпатии:
    0

    1. $result = mysqli_query(«INSERT INTO `players` (login,password,gender) VALUES ($login,$password,$gender);

    не выполняется запрос
    и посмотреть ошибку тоже не могу, писал так для ВЫВОДА ошибки

    Подскажите, пожалуйста, что не так?


  2. ADSoft

    подключение к бд уже есть?
    покажите полностью код
    от подключения и до выполнения запроса


  3. Пэлт

    С нами с:
    1 апр 2020
    Сообщения:
    103
    Симпатии:
    0

    да, конечно

    1.     public static function connect()
    2.     {// @TODO Change the data connection
    3.         @self::$link = mysqli_connect(‘localhost’, ‘база данных’, ‘пароль’, ‘имя пользователя)  // имя пользователя и бд одинаковые все равно
    4.                       or die(‘No connect (‘ . mysqli_connect_errno() . ‘)
    5.                                             . mysqli_connect_error());
    6.     // @TODO Change the encoding
    7.        mysqli_set_charset(self::$link, ‘utf8‘);
    8.    public static function escape($data)
    9.            $data = array_map(‘self::escape‘, $data);
    10.            $data = mysqli_real_escape_string(self::$link, $data);
    11.    public static function Query($sql, $print = false)
    12.        $result = mysqli_query(self::$link, $sql);
    13. // @TODO Remove the following lines when in production mode
    14. // ……………………………………….  
    15.        if($result === false || $print === 1)
    16.            $error =  mysqli_error(self::$link);
    17.            $trace =  debug_backtrace();
    18.                preg_match(«#’(.+?)‘#is», $error, $out);
    19.            $head = $error ? ‘<b style=«color:red»>MySQL error: </b><br>
    20.             <b style=«color:green»>‘. $error .’</b><br><br>‘:NULL;  
    21.            $error_log = date(«Y-m-d h:i:s») .’ ‘. $head .’
    22.             <pre><span style=«color:#990099»>
    23.            . str_replace($out[1], ‘<b style=«color:red»>‘. $out[1] .’</b>‘, $trace[0][‘args‘][0])
    24.             <b>File: </b><b style=«color:#660099»>‘. $trace[0][‘file‘] .’</b><br>
    25.             <b>Line: </b><b style=«color:#660099»>‘. $trace[0][‘line‘] .’</b>‘;
    26. // ……………………………………….
    27.    static public function result($res, $row, $column = 0)
    28.        while($data = mysqli_fetch_array($res, MYSQLI_BOTH))
    29.    function deprecated($function)
    30.       $trace =  debug_backtrace();
    31.       exit(‘<strong style=«color:red»>Fatal error:</strong><br>
    32.           .’Function <a href=«http://php.net/’. $function .'»>‘. $function .’</a>
    33.           .’ is deprecated and has no analog in <br>
    34.           .’<strong>‘. $trace[0][‘file‘] .’</strong>‘        
    35.           .’ on line <strong>‘. $trace[0][‘line‘] .’</strong>

    версия пхп 7.4 указана. это подключение к бд сверху.
    а в файле регистрация.пхп
    подключается бд через
    include ‘/sys/bd.php’;


  4. MouseZver

    С нами с:
    1 апр 2013
    Сообщения:
    7.562
    Симпатии:
    1.284
    Адрес:
    Лень

    потому что данные вставляешь НАРУШАЯ синтаксис запроса


  5. Пэлт

    С нами с:
    1 апр 2020
    Сообщения:
    103
    Симпатии:
    0

    не мог бы написать как правильно этот запрос прописать?


  6. MouseZver

    С нами с:
    1 апр 2013
    Сообщения:
    7.562
    Симпатии:
    1.284
    Адрес:
    Лень

    нет, не смогу, опыта не хватает.


  7. Пэлт

    С нами с:
    1 апр 2020
    Сообщения:
    103
    Симпатии:
    0


  8. ADSoft

    строковые значения должны быть в кавычках

    1. (‘$login’,’$password’,’$gender’)


  9. Edward-T

    С нами с:
    18 дек 2020
    Сообщения:
    12
    Симпатии:
    0

    зачем тебе mysqli, пользуй PDO

    1.     private static $instance = null;
    2.     public function getInstance()
    3.         if (is_null(self::$instance))
    4.             self::$instance = new PDO(
    5.                 «mysql:host=localhost;dbname=testdb»,

    добавить забыл обработку PDOException

    данный синглтон дополни методами на insert, delete, update, select


  10. MouseZver

    С нами с:
    1 апр 2013
    Сообщения:
    7.562
    Симпатии:
    1.284
    Адрес:
    Лень

    а зачем пдо, когда есть мускуль ?

Warning mysqli_error() expects parameter 1 to be mysqli, null given inВводная: есть PHP файл который регистрирует пользователей в базе данных. Вроде бы все хорошо, но пользователь не записывается в базу.

Перед записью открывается соединение, выполняются проверки. То есть соединение с базой данных есть. Сам SQL-запрос составлен правильно, все хорошо. Но данные не записываются в базу, хоть ты тресни.

Возникают два вопроса:

  1. Почему не работает.
  2. Как понять, почему не работает.

Второй вопрос более приоритетный, и что?

Для того, что бы посмотреть ошибки, нужно после запроса:

$result = $con->query("INSERT INTO ... запрос ...");

Добавить код, в итоге получиться:

$result = $con->query("INSERT INTO ... запрос ...");
if (!$result) {
var_dump(mysqli_error($result));
}

При этом мы получим ошибку PHP. Это важно понимать, тут ключевая фраза ошибка PHP.
Я получал следующие ошибки:

  • Warning: mysqli_error() expects parameter 1 to be mysqli, null given in /var/www/fastuser/data/www/webinsert.ru/reg.php on line 133.
  • Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in /var/www/fastuser/data/www/webinsert.ru/reg.php on line 133

Пользователи на просторах интернета пишут всякий бред, из разряда ты что, не умеешь читать ошибки что ли? Да, от души братуха, о чем говорят ошибки:

MySQL ожидает параметр 1, а получает NULL  или логику. То есть ничего не понятно.

Warning mysqli_error() expects parameter 1 to be mysqli, null given in

Нам нужно понять, в чем ошибка SQL. Я пробовал выполнить запрос на сервере, но он срабатывал.

Что бы понять в чем ошибка SQL нужно перед соединением с БД прописать код:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

И, о чудо, после ввода данных в форму регистрации появилась ошибка MySQL:

data too long for column email at row 1

И теперь стало все понятно.

Данные слишком длинные для столбца ’email’ почты в строке 1.

Смотрю в базу и вижу.

varchar 20

А количество символов в поле e-mail которое я вводил было 22. Вот в чем моя ошибка.


Анатолий Бузов

Анатолий Бузов / об авторе

Обучаю HTML, CSS, PHP. Создаю и продвигаю сайты, скрипты и программы. Занимаюсь информационной безопасностью. Рассмотрю различные виды сотрудничества.


Понравилась статья? Поделить с друзьями:
  • Mysqli error не выводит ошибку
  • Mysqli error no database selected
  • Mysqli error log
  • Mysqli error exception
  • Mysqli error 500