define('DB_NAME','swiftx');
define('DB_USER','root');
define('DB_PASSWORD','123456');
define('DB_HOST','localhost');
if (isset($_POST['submit'])){
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}else{
echo("Database Connected");
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$value = $_POST['name'];
$value2 = $_POST['attendance'];
$sql = "INSERT INTO people (Name,Email) VALUES ('$value','$value2')";
if(!mysqli_query($sql)){
die ("ERROR:". mysqli_error()); //error here <<<<<<<<
}
}
mysqli_close($connection);
why is mysql returing error "mysqli_query() expects at least 2 parameters"
i am following a website tutorial , i double check again and again , i have done noting wrong , can anyone help me fix it ? i have no idea what i doing wrong.
for mysqli_query() we need to pass two parameters
$query
$link_identifier
in your case $query is $sql and $link_identifier is $connection..it mean you need to use mysqli_qeury() in this way
mysqli_query($sql, $connection)
Your error "mysqli_query() expects at least 2 parameters" is pretty self-explanatory. It expects two parameters you are giving just one.
Try this:
if(!mysqli_query( $connection, $sql) ){
Related
I am creating a web based application, and I am using PDO for my database. I have a query that selects everything from login table where username=something and password=something.
My code:
$query = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindParam(':username',$username);
$query->bindParam(':password',$password);
$query->execute();
However I want to check if the query returned true or false. For example in mysql we used to say:
$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password' ");
if($query == false){
die(mysql_error());
}
My question is, how do I check if the query returned false or true using PDO and gives an error? This will help me get errors on my code during development.
What am I going to replace the mysql_error() with?
We set PDO in exception mode.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
We wrap queries with try/catch block. If an Exception is thrown, we catch it. That's the equivalent of using if(!mysql_query($query)) echo mysql_error();
Your example would be
try
{
$query = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindParam(':username',$username);
$query->bindParam(':password',$password);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo "Whoopsie, an error occurred! Message: ". $e->getMessage();
}
Originally I got this error
Error: 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 '' at line 1
but I narrowed it down to this block of code
$query = "SELECT Priority FROM mathhw WHERE MHID=$row";
echo $query;
$querycon = mysqli_query($con,$query);
while($row = mysqli_fetch_row($querycon))
{
$priority = $row[0];
echo $priority;
}
if($priority==0)
{
$sql="UPDATE mathhw SET Priority = 1 WHERE MHID=$row";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: math.php");
}
else if($priority == 1)
{
$sql="UPDATE mathhw SET Priority = 0 WHERE MHID=$row";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: math.php");
}
I did some trial and error and it seemed like the WHERE condition is giving me trouble. I hard-coded it, and I took it out completely and it did what I wanted it to do. I think it is problem with my quotes? I don't think I'm supposed to put quotes around numerical values but I think variables are a different case. Can someone help me out.
From the block of code you have here, the error is being thrown in one or the other of the UPDATE queries because you are reusing $row in those queries after having set it to either an array of strings or NULL from the fourth line in your code:
while($row = mysqli_fetch_row($querycon))
...
See http://www.php.net/manual/en/mysqli-result.fetch-row.php.
Then, you're reusing it here without modification.
...
$sql="UPDATE mathhw SET Priority = 1 WHERE MHID=$row";
Given the syntax error ending with near '' at line 1, your SELECT probably returned nothing, set
$row to NULL and then replaced $row with "" in your query.
A quick tip that really helped me with MySQLi is the following function:
http://www.php.net/manual/en/mysqli.real-escape-string.php
Take a look at the example, using the procedural style, like your code above:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
$city = "'s Hertogenbosch";
/* this query will fail, cause we didn't escape $city */
if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("Error: %s\n", mysqli_sqlstate($link));
}
$city = mysqli_real_escape_string($link, $city);
/* this query with escaped $city will work */
if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) {
printf("%d Row inserted.\n", mysqli_affected_rows($link));
}
mysqli_close($link);
?>
One last note: in your WHERE clause, what you have is only correct if MHID is not a string typed column. If MHID is a varchar, for example, you would need to quote the $row as '$row', like so:
$sql="UPDATE mathhw SET Priority = 1 WHERE MHID='$row'";
That's when the mysqli_real_escape_string() function becomes REALLY useful.
I have been trying to get this code to update, and it just will not work. I've been re-reading it and looking at other examples for hours and need some help to get this to work. It is a basic UPDATE script for a membership table in mysql database. I have mysql version 5.0.91. Nothing I have tried is working. When uploaded and tested in browser, returns echo "update query failed" I bolded the part where it is failing. I just can't find out why. When I check mysqladmin, the table is not updated.
$host="mysqlhost"; // Host name
$username="mysqlusername"; // Mysql username
$password="mysqlpassword"; // Mysql password
$db_name="mydbname"; // Database name
$tbl_name="brothers"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$mymname=$_POST['mymname'];
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$myconfirmpassword=$_POST['myconfirmpassword'];
$mysnumber=$_POST['mysnumber'];
$myemail=$_POST['myemail'];
if ($mypassword !== $myconfirmpassword) {
die ("passwords do not match. Try again!");
if (isset($_COOKIE['fname'])) {
$myfname = ($_COOKIE['fname']);
}
else {
die('could not find cookie fname');
}
if (isset($_COOKIE['lname'])) {
$mylname = ($_COOKIE['lname']);
}
else {
die('could not find cookie lname');
}
$sql="SELECT * FROM $tbl_name WHERE fname='$myfname' AND lname='$mylname'";
$result=mysql_query($sql)or die("no sql");
while($row = mysql_fetch_array($result))
{
$fname=$row['fname'];
if (!$fname) {
die('variable not received');
}
$lname=$row['lname'];
$position=$row['position'];
$committee=$row['committee'];}
if($mypassword==$myconfirmpassword) {
$query= "UPDATE brothers
SET `mname`='$mymname' WHERE `fname` ='$fname'";
$chechresult= mysql_query($query) or die (mysql_error());
if (!$checkresult) echo 'update query failed';
elseif ($checkresults) {
echo'update query success';
setcookie('position', $position, time()+86400,'/');
setcookie('committee', $committee, time()+86400,'/');
$headsuccess=header( "location:done_registration.php");
$headsuccess;
if (!$headsuccess) {
die('Could not redirect success registration'); }
}
}
else{
$headlogin=header( "location:error_registration.php");
$headlogin;
if (!$headlogin) {
die('Could not redirect registration error'); }
}
$chechresult= mysql_query($query) or die (mysql_error());
if (!$checkresult) echo 'update query failed';
you misspelled "k" with "h" in "$chechresult="
Try to print $query string that contains the UPDATE order and after execute it in mysql console.
You've misspelled $chechresult - should be $checkresult; also, $fname should be $myfname!
It is probably worth echoing out $query to the screen, and trying that directly in your database - either on your console or in phpMyAdmin. Since $fname is empty (wrong var) your WHERE clause is wrong; at a guess it is affecting zero rows, and so is executing correctly.
Bear in mind that you have some SQL injection security issues in this code - make sure you escape your values before adding them to a query. Better yet, if you upgrade to PDO, you can use parameterisation, which will do the escaping for you.
I am writing a code that will check 2 different tables to determine the privileges the user will have. The code looks like this:
$query1 = ("SELECT 1 FROM `customers` WHERE `Email` = '$email' AND `Password` = '$password'");
$query2 = ("SELECT 1 FROM `admins` WHERE `Email` = '$email' AND `Password` = '$password'");
$result1 = mysql_query($query1) or die(mysql_error());
$result2 = mysql_query($query2) or die(mysql_error());
if (mysql_num_rows($result1) == 1) {
// Log user in as a Customer
exit;
} else if (mysql_num_rows($result2) == 1) {
// Log user in as an Admin.
exit;
} else {
// Direct user to registration page.
}
Can anyone look at this and tell me if there would be any security risk by doing it this way? Thank you in advance for your help!
Firstly you have a change that your code is only known by you.
Secondly you have to check the input data. email and password area is not safety. You should prevent SQL injection. Otherwise your code is not secure.
By the way i'm offering you IP restricted login for admins. I'm using this. And it is more secure.
One big problem here is that the code is vulnerable for sql injections.
Which basicly means that the user could put code in the email or password form to bypass the check you have here.
A start would be to perform the following to your input BEFORE you use them in your query:
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
Though, the mysql library is not recommended by php, rather read about prepared statements in pdo here: http://www.php.net/manual/en/ref.pdo-mysql.php
But you can try the mysql_real_escape_string to have a first security measure against sql injections.
This is insecure if for example my password was
OR 1=1
I get access. Use mysql prepared statements
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("SELECT 1 FROM customers WHERE Email = (?) AND Password = (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("ss", $email, $password)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>
I'm a beginner and I have a error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in C:\Program Files\VertrigoServ\www\index.php on line 35
and the code...
$sresult = mysql_query("SELECT code, location FROM banners");
while ($row_s = mysql_fetch_array($sresult))
{
$banner[$row_s["location"]]=$row_s["code"];
}
Try this
$sresult = mysql_query("SELECT code, location FROM banners");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row_s = mysql_fetch_array($sresult))
{
$banner[$row_s["location"]]=$row_s["code"];
}
And check what the error is.
Something is wrong with the query.
try:
$result = mysql_query("..");
if(!$result){
echo "Query error: " . mysql_error();
}