Data is not inserting into table? - php

GYZ i dont know why data is not inserting in my data base #Mysql
. infact im using mysqli_connect and mysql_connect both ,I'm still facing same prob ..this is my code:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db='school';
#mysqli_connect($servername, $username, $password);
#mysqli_select_db($db); //or die ('not Connect to db ');
if(isset($_GET['submit'])) {
$sid= $_GET['sid'];
$sname= $_GET['sname'];
$fname= $_GET['fname'];
$order= #mysqli_query("insert into school (sid,sname,fname) values ('$sid','$sname','$fname');");
if ($order) {
echo '<br>Input data is successful';
} else {
echo '<br>Input data is not valid';
}
} ?>

I revisited the question and posted the following, seeing that nobody posted one.
You didn't pass the db connection to mysqli_select_db() nor for mysqli_query() and need to assign a variable to the connection first.
Both of those require it in mysqli_ and you may have been accustomed to mysql_ in the past. MySQLi_ is different than MySQL_ when it comes to certain functions that needs a connection.
Sidenote: The # symbol is an error suppressor. Remove it during testing/development.
Another sidenote: Both your database and table bear the same name of school. Make sure that this is correct.
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$db='school';
$connect = mysqli_connect($servername, $username, $password, $db);
if($connect){
echo "Connected";
}
else {
echo "Error: " . mysqli_error($connect);
}
// This isn't needed. You can pass all 4 parameters in one shot.
// $database = mysqli_select_db($connect, $db); //or die ('not Connect to db ');
if(isset($_GET['submit'])) {
$sid= $_GET['sid'];
$sname= $_GET['sname'];
$fname= $_GET['fname'];
$order= mysqli_query($connect, "INSERT INTO school (sid,sname,fname) VALUES ('$sid','$sname','$fname');");
if ($order) {
echo '<br>Input data is successful.';
} else {
// Uncomment the one below once everything is ok.
// echo '<br>Input data is not valid.';
// Comment this below once there are no errors.
echo "There was an error: " . mysqli_error($connect);
}
}
References:
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqli.select-db.php
http://php.net/manual/en/mysqli.query.php
Check for errors also via PHP and the query:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
And make sure you're running this off a webserver, or if local that PHP/MySQL are installed, running properly and using http://localhost as opposed to file:///.
Your code is also open to an SQL injection, use a prepared statement.
References:
https://en.wikipedia.org/wiki/SQL_injection
https://en.wikipedia.org/wiki/Prepared_statement
Footnotes:
You seem to want to use this in a table. <form> cannot be child of <table> if you are using those tags outside of the form which wasn't posted in your question; there are stray <td></td> tags.

Related

How can i change my current mysqli procedural way into pdo where i can call store procedure

i'm currently using mysqli procedure to write code which i want to change it in pdo because in mysqli i'm mysqli_escape_string whereas i dont how to change it in pdo
here is my mysqli attempt
<?php
if(isset($_GET['id1'])){
$id=$_GET['id1'];
$result=GetWordsById(mysqli_escape_string($conn,$id));//Here GetWordsById is a function calling store procedure
if(mysqli_num_rows($result)>0)
$row=mysqli_fetch_array($result);
$word=$row['word'];
$meaning=$row['meaning'];
$synonym=$row['synonym'];
$antonym=$row['antonym'];
}
?>
below is my function.php
function GetWordsByID($id){
include("conn.php");
$result=mysqli_query($conn,"CALL GetWordsById($id)");//Here GetWordsById is my store procedure
return $result;
}
Here i want to know how i can change both function and main php script calling function where i'm using mysqli_escape_string to pdo i'd appreciate some help
To PDO,
your db connection file will look like this,
<?
$servername = "localhost";
$username = "username"; // Enter your db username
$password = "password"; // Enter your db password
$dbname = "myDBPDO"; // Enter your db name
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Now comes your code,
<?
if(isset($_GET['id1'])){
$id=$_GET['id1'];
$result=GetWordsById($id);//Here GetWordsById is a function calling store procedure
if($result->fetchColumn()>0){
$row=$result->fetch(PDO::FETCH_ASSOC);
$word=$row['word'];
$meaning=$row['meaning'];
$synonym=$row['synonym'];
$antonym=$row['antonym'];
}
}
and function,
function GetWordsByID($id){
include("conn.php");
$result=$conn->prepare(" ");//Here sql statement
$result->execute();
return $result;
}

Call MySQL stored procedure from PHP

I have looked at several examples on how to call a MySQL stored procedure from PHP but none have helped me. The stored procedure works when run inside PHPMyAdmin but I am having trouble calling it from the web.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
header('refresh:1; url=schedule_main_scores.php');
else
echo "failed";
?>
There's 2 problems here.
You're querying twice and using the wrong variable, being $sql instead of $result.
$result = mysqli_query($conn,"CALL standings_build()");
if (mysqli_query($conn,$sql))
^^^^^^^^^^^^ calling the query twice
^^^^ wrong variable, undefined
all that needs to be done is this:
if ($result)
and an else to handle the (possible) errors.
Error reporting and mysqli_error($conn) would have been your true friends.
http://php.net/manual/en/function.error-reporting.php
http://php.net/mysqli_error
Side note: You really should use proper bracing techniques though, such as:
if ($result){
echo "Success";
}
else {
echo "The query failed because of: " . mysqli_error($conn);
}
It helps during coding also and with an editor for pair matching.

mysqli_connect() isn't selecting database? and can't insert data

I've got this code
<?php
$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="mydb";
$db_connect=mysqli_connect($db_host, $db_username,$db_password, $db_name);
//check connection
if (mysqli_connect_error()){
echo "Failed to connect to MySQL:" .mysqli_connect_error();
} else{
echo "Connection successful" ;
}
?>
When i run the code it shows "Connection successful" but when i input data into a table that is in the database it gives me an error "No database selected"
I tried the code below and it seems to work, other than the fact that the Auto increment value (ID) isn't passed into the database so it gives me an error which means that "the data passed in row 1 doesn't match the datatype. "(Shouldn't it not be required to be entered, and with each insert query gets updated automatically?) I am passing values to the table using and insert statement and not in array form, maybe?
<?php
error_reporting(1);
$connect_error = 'Sorry, we\'re experiencing connection problems.';
mysql_connect('localhost','root','') or die($connect_error);
mysql_select_db('mydb') or die($connect_error);
?>
I was asked to provide the code i'm using for inserting data into the table.
<?php
require_once ('dbconnect.php');
$title= "my title";
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$class = $_POST['class'];
$type = $_POST['type'];
$description = $_POST ['description'];
$date = date(d-m-y);
$sql= "INSERT into mytable values ('username, password, class, type, description')" ;
$qry= mysql_query($sql) ;
if (!$qry) {
echo "Something went wrong: " . mysql_error();}
else echo "Finished successfully";
}
?>
Are you mixing mysqli and mysql.
use below code to fire mysql query
mysqli_query($db_connect,$sql);
replace this line
$qry= mysql_query($sql) ;
to
$qry= mysqli_query($db_connect,$sql);
Latest Version of php uses mysqli object (mysql improved) insted of methods for accessing mysql database.
<?php
$db_host="localhost";
$db_username="root";
$db_password="";
$db_name="mydb";
$db_connect=new mysqli($db_host, $db_username,$db_password, $db_name);
//check connection
if ($db_connect -> connect_error)
{
echo "Failed to connect to MySQL:".$db_connect->connect_error;
}
else{
echo "Connection successful" ; }
?>
I had two mistakes, one was mixing mysqli in the dbconnect.php while using mysql_query in the other page. And then I was confused about the second parameter to use with mysqli_query other than the insert statement, used the connection variable and it now works.

PHP form not inserting into mySQL database

hi guys thanks if you can tell me what error i need help guys thanks for help me
<?php
$servername = "localhost"; $username = "root"; $password = "";
$dbname = "kurd";
mysql_connect("localhost","root","","kurd") or die ("not connect data base");
mysql_select_db("kurd") or die ("no found table");
if(isset($_POST['submit'])){
$name = $_POST['name'];$lastname = $_POST['lastname'];
$password =_POST['password'];
$query =" INSERT INTO kurdstan (name,lastname,password) VALUES ('$name','$lastname','$password')";
if(mysql_query($query)){
echo "<h3>THANKS FOR INSERT DATA GOOD LUCK</h3>";
}
}
?>
In your code add an else to,
if(mysql_query($query)){
echo "<h3>THANKS FOR INSERT DATA GOOD LUCK</h3>";
}
resulting in,
if(mysql_query($query)){
echo "<h3>THANKS FOR INSERT DATA GOOD LUCK</h3>";
}
else {
echo 'MYSQL Error: ' . mysql_error();
}
and you will probably see an error instead of your message which should help you to track down the problem.
NOTE
The mysql extension is now depreciated, you should use mysqli http://php.net/manual/en/book.mysqli.php or PDO http://php.net/manual/en/book.pdo.php. You should also read up on SQL injection - your data needs escaping before being used in a query string.

Trying to insert data into a database using PHP / Mysqli

I'm trying to execute an Insert query to write data into a Database. I'm using Mysqli and PHP.
The code looks OK for me. However, every time I go to the webpage to check if the form works, the query gets executed an a new row is created in the DB (empty).
I'm pretty sure there is something wrong with the last if statement. Could you advise?
BTW, the snippet is only for the PHP to execute the sql query, since the form is working just fine.
Thanks!
$servername = "localhost";
$username = "root";
$password = "mysqlpassword";
$dbname = "bowieDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$album = $_POST['album'];
$relyear = $_POST['relyear'];
$label = $_POST['label'];
$chart = $_POST['chart'];
$track1 = $_POST['track1'];
$track2 = $_POST['track2'];
$track3 = $_POST['track3'];
$track4 = $_POST['track4'];
$track5 = $_POST['track5'];
$sql = "INSERT INTO Albums (album, relyear, label, chart, track1, track2, track3, track4, track5)
VALUES ('$album', '$relyear', '$label', '$chart', '$track1', '$track2', '$track3', '$track4', '$track5')";
$result = mysqli_query($conn, $sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You are mixing Procedural and Object Orientated SQL interactions.
This is Procedural:
$result = mysqli_query($conn, $sql);
This is Object Orientated:
$conn->query($sql)
You can not use both with the same connection details, you should do one or the other throughout your code. The best one to use is Object Orientated approach, so rework the Procedural code to:
$result = $conn->query($sql);
if ($result) {
...
So actually you can simply remove the line starting $result = ... and let the IF statement query you already have handle itself.
Other notes:
Use MySQL error feedback such as checking if(!empty($conn->error)){print $conn->error;} after SQL statements. See example code below...
Use the following PHP error feedback too, set at the very top of your PHP page:
...
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
you need to read up and be aware of SQL injection that can destory your database should someone POST data that also happens to be MySQL commands such as DROP.
Code for Comment:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//run SQL query you already have coded and assume
// that the form has been filled in.
$result = $conn->query($sql);
if ($result) {
//all ok
}
if(!empty($conn->error)) {
print "SQL Error: ".$conn->error;
}
}
use
1. if(isset($_POST['Submit'])){//your code here }
and
2. if($result){...
if you are using procedural method

Categories