Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in C:\xampp\htdocs\arun\login.php on line 9
Code:
$db_select = mysql_select_db('my_db', $con);
$username = $_GET['username'];
$password = $_GET['password'];
$role = $_GET['role'];
$result = mysql_query("Insert into table1(Username,Password,Role) values (Username='$username', Password='$password',Role='$role') ",$con);
$row = mysql_fetch_array($result);
if ( mysql_error() )
{
die ( mysql_error());
}
$row_PK = mysql_fetch_assoc($row);
mysql_close($con);
?>
Replace
$result = mysql_query("Insert into table1(Username,Password,Role) values (Username='$username', Password='$password',Role='$role') ",$con);
with
$result = mysql_query("Insert into table1(`Username`,`Password`,`Role`) values ('$username', '$password','$role') ",$con);
You don't have to assign the value to the column on your INSERT query as you have done. Just map the values as shown above.
Apart from the above issues... Dissecting your code ..
The main issue with your code is you are doing an INSERT but you are expecting a resultset as you have done a SQL SELECT which is wrong.
You need to change your code like this..
The below code is just an illustration to tell you what you had done was actually wrong. Do not use this code ! You first need to migrate to the latest database API provided for you in the side note section.
$db_select = mysql_select_db('my_db', $con);
if(isset($_GET['username'],$_GET['password'],$_GET['role']))
{
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$role = mysql_real_escape_string($_GET['role']);
$result = mysql_query("Insert into table1(`Username`,`Password`,`Role`) values ('$username', '$password','$role') ",$con);
if (!$result)
{
die (mysql_error());
}
else
{
echo "Record Inserted";
}
mysql_close($con);
}
SideNote
The (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead,the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
For a INSERT query the return value isn't a resource, it's a TRUE on success or FALSE on error.
A resource is returned for a SELECT, SHOW, DESCRIBE or EXPLAIN query.
this is your solution change your query to
$result = mysql_query("Insert into table1(Username,Password,Role) values ('$username', '$password','$role') ",$con);
your query should be like this
$result = mysql_query("Insert into table1(Username,Password,Role) values ('$username', '$password','$role') ",$con);
NOTE: mysql_* is deprecated use mysqli_* OR PDO
Related
I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);
I'm trying to retrieve the last id number inserted with mysql_insert_id() but always return 0, my id field is auto increment so I don't know why it returns 0 thanks. please help
include 'C:\xampp\htdocs\Student_evaluation\functions.php';
if(!loggedin())
{
header("Location: http://localhost/dev/userarea.php");
exit();
}
if(isset($_POST['submit']))
{
//get data
$name = $_POST['name'];
$f_lastname = $_POST['f_lastname'];
$second_lastname = $_POST['second_lastname'];
$student_number = $_POST['student_number'];
$semester_year = $_POST['semester_year'];
$course = $_POST['course'];
$section = $_POST['section'];
$grade = $_POST['grade'];
$student_perform = $_POST['student_perform'];
$comment_box = $_POST['comment_box'];
$sql = "INSERT INTO `students`(`name`, `first_lastname`, `second_lastname`, `numero_estudiante`, `semester`, `course`, `section`, `f_grade`, `students_perform`, `comments`)
VALUES ('$name','$f_lastname','$second_lastname','$student_number','$semester_year','$course','$section','$grade','$student_perform','$comment_box')";
$con = mysqli_connect("localhost","root","","rememberme");
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysql_insert_id();
}
You're using one library (mysqli) to perform the query, then another (mysql) to obtain the auto-increment ID. That can't work. Among other issues, you haven't even connected to the database with the second library!
Consistently use mysqli or, better yet, PDO, which will help you plug your blinding security flaw.
You should do something like this (using mysqli_insert_id):
$con = mysqli_connect("localhost","root","","rememberme");
$sql = "INSERT INTO ...";
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysqli_insert_id($con);
mysql_insert_id and mysqli_insert_id are both different and you are using mysqli so use mysqli_insert_id instead of mysql_insert_id and it's better to use mysqli instead of mysql.
Busy really frustrating myself here. I am busy trying to write a simple login script that validates a login against the database.
However i keep on getting:
Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in
here is my code.... when i run the query on sql workbench it works 100%
<?php
// Grab User submitted information
$email = $_POST['users_email'];
$pass = $_POST['users_pass'];
// Connect to the database
$con = mysql_connect('localhost','root','');
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysql_select_db('arctecs',$con);
$result = mysql_query('SELECT users_email, users_pass FROM users WHERE users_email = $email');
$row = mysql_fetch_array($result);
if($row['users_email']==$email && $row['users_pass']==$pass)
echo'You are a validated user.';
else
echo'Sorry, your credentials are not valid, Please try again.';
?>
This is not correct
'SELECT users_email, users_pass FROM users WHERE users_email = $email'
better way is
"SELECT users_email, users_pass FROM users WHERE users_email = '$email'"
Need to wrap the string data in single quote.
The POST data is directly being used in the query which is not good. Start using PDO prepared statements to avoid sql injections or at-least sanitize data as
$email = $_POST['users_email'];
$pass = $_POST['users_pass'];
$con = mysql_connect('localhost','root','');
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
$email = mysql_real_escape_string($email);
Variables will not be parsed under single quotes. Rewrite like below
$result = mysql_query("SELECT `users_email`, `users_pass` FROM `users` WHERE `users_email` = '$email'") or die(mysql_error());
Warning : You script is prone to SQL-Injection attack. You need to switch to Prepared Statements.
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
it happens when your query is not executed so use mysql_error() to know the error
$result = mysql_query("SELECT users_email, users_pass FROM users WHERE users_email = $email") or die(mysql_error());
mysql_query will return false on errors.
You also should consider to use the mysqli extension. The mysql extensions is deprecated as of PHP 5.5.0.
See: http://www.php.net/manual/en/function.mysql-query.php
try this:
$result = mysql_query('SELECT users_email, users_pass FROM users WHERE users_email = "$email"');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
I have some PHP problems regarding my PHP code
I create function that update database, for changing password. Here's my syntax
function changePassword($username, $password, $salt){
$query = "UPDATE mt_user SET password = '". $password ."' , salt = '". $salt . "' WHERE username = '". $username ."'";
$result = mysql_query($query);
if ($result == false){
$num_rows = mysql_error();
} else {
$num_rows = mysql_num_rows($result);
}
mysql_close();
return $num_rows;
}
I try this function by create some script:
echo changePassword('user1','test','test_salt');
The database value is updated but, the function is showing some warnings
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in.....
What's wrong with the code? Because I don't see any errors.
mysql_num_rows() is the wrong function here because what is does
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.
To see how many rows were changed, use mysql_affected_rows().
$num_rows = mysql_affected_rows();
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
for update and insert queries you need to use mysql_affected_rows. mysql_num_rows only works for select statement.
A little advice: replace mysql to mysqli. It's more secure. This example is with this one.
function changePassword($username, $password, $salt){
$query = "UPDATE mt_user SET password = '". $password ."' , salt = '". $salt . "' WHERE username = '". $username ."'";
$result = mysqli_query($connection,$query);
if ($result){
$num_rows = mysqli_affected_rows($connection);
} else {
$num_rows = mysqli_error($connection);
}
mysql_close();
return $num_rows;
}
$sql_comp5 ="INSERT INTO `tiquets` (`Id_Tiquet`) VALUES (NULL); SELECT LAST_INSERT_ID()";
$result8 = mysql_query($sql_comp5);
$flag_control=0;
while ($row = mysql_fetch_assoc($result8, MYSQL_BOTH))
{
$flag_control=$flag_control+1;
$id_t[$flag_control]=$row['LAST_INSERT_ID()'];
}
for ($buc = 1; $buc <=$flag_control; $buc++)
{
$id_tiquet=$id_t[$buc];
}
I am doing the correct? Or i'm wrong?
Very thanks!!
You can't do two queries use mysql_* functions. You need mysqli::multi_query() for that. To get the last insert ID using mysql_* use mysql_insert_id():
$sql_comp5 ="INSERT INTO `tiquets` (`Id_Tiquet`) VALUES (NULL);";
$result8 = mysql_query($sql_comp5);
$id = mysql_insert_id($result8);
Remove the second query - and use php's mysql_insert_id()
$sql_comp5 ="INSERT INTO tiquets (Id_Tiquet) VALUES (NULL)";
$result8 = mysql_query($sql_comp5);
$insertedId = mysql_insert_id();