mysqli_error: updating tables (Procedural style) - php

I am using PHP to try and update information I have in a mysqli table. I have decided to try and use mysqli rather than mysql. Unfortunately I cant seem to find my answer anywhere because im also trying to complete it Procedural style, as I have no knowledge of OOP and all tutorials (that i have found) are in OOP.
Below is the script I have created. I have added comments to say what I think each command is doing.
<?php
DEFINE('DB_USER', 'root');
DEFINE('DB_PASS', 'password');
DEFINE('DB_NAME', 'test');
DEFINE('DB_HOST', 'localhost');
//connect to db
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_connect_error($dbc));
mysqli_set_charset($dbc, 'utf8');
//form not submitted
if(!isset($_POST['submit'])){
$q = "SELECT * FROM people WHERE people_id = $_GET[id]";//compares id in database with id in address bar
$r = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r, MYSQLI_ASSOC);//returns results from the databse in the form of an array
}else{//form submitted
$q = "SELECT * FROM people WHERE people_id = $_POST[id]";//compares id in database with id in form
$r2 = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);//returns results from the database in an array
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$hobby = $_POST['hobby'];
$id = $_POST['id'];
//mysqli code to update the database
$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
//the query that updates the database
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
//1 row changed then echo the home page link
if(mysqli_affected_rows($dbc) == 1){
echo "home page";
}
}
?>
The update form
<form action="update.php" method="post">
<p>First name<input type="text" name="fname" value="<?php echo "$person[people_fname]" ?>" /></p>
<p>Last name<input type="text" name="lname" value="<?php echo "$person[people_lname]" ?>" /></p>
<p>Your age<input type="text" name="age" value="<?php echo "$person[people_age]" ?>" /></p>
<p>Your hobby<input type="text" name="hobby" value="<?php echo "$person[people_hobby]" ?>" /></p>
<input type="hidden" name="id" value="<?php echo $_GET['id'] ?>" />
<input type="submit" name="submit" value="MODIFY" />
</form>`
When I submit the form I get the following error message
Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\sandbox\update.php on line 39
I realize this is telling me the issue is with
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
So I have tried to put the sqli code in as the second parameter (i realize this is the same as putting the variable in, but it was a last resort), but it didn't seem right and still didn't work. I have also looked a php.net but couldn't work out the answer from the example they have given
Please advise, I thought this was meant to be simple?

$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
You need to quote out the variables:
$update = "UPDATE people
SET people_fname = '$fname',
people_lname = '$lname',
people_age = '$age',
people_hobby = '$hobby'
WHERE people_id = '$id'";
HOWEVER
You should look into bound parameters - you're taking user input and writing it straight into your database, which means that a malicious user can do all sorts of mischief.
Have a look at the manual page for mysqli's bind_param - there are plenty of example code snippets.

Don't pass $r to mysqli_error. It accepts an optional mysql link, but not a query result anyway.
In your case, the query is executed. That evaluates to false, which is assigned to $r. The assignment evaluates to false, causing you to call die(mysqli_error($r)) with $r being false.
I think you meant to pass $dbc to mysqli_error.

Looks to me like the problem is with the database connection ($dbc). Because you are using
#mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME)
The '#' may be hiding the connection error somehow.
Also, please tell me you're doing data sanitisation in real life, right? If not, you have to run mysqli_real_escape_string() on all the POST and GET data.

you wrote
//returns results from the database in an array
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);
but you should write
//returns results from the database in an array
$person = mysqli_fetch_array(MYSQLI_ASSOC);

Related

The result of my search isn't appearing using php code

<html>
<body>
<form action="checkorderstatus.php" method="post">
<input id="search" type="text" placeholder="Type here">
<input id="submit" type="submit" value="Search">
</form>
</body>
</html>
<?php
require_once 'loginorder.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) {
die($conn->connect_error);
}
if (isset($_POST['submit']));
$query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'";
$result = $conn->query($query); //run the query and get the result
if (!$result) {
die($conn->error);
}
$rows = $result->num_rows;
$query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'";
$result = mysqli_query($conn, $query);
($row = mysqli_fetch_row($result)); {
echo $row['1'];
print_r($row);
}
?>
I'm trying to display the status description when the statusid is entered into the search but it's not displaying anything other than Array ( [0] => product is in transit )
and I'm getting 3 errors
Notice: Undefined variable: search in
C:\wamp64\www\groupproject\checkorderstatus.php on line 20 Notice:
Undefined variable: search in
C:\wamp64\www\groupproject\checkorderstatus.php on line 28 Notice:
Undefined offset: 1 in C:\wamp64\www\groupproject\checkorderstatus.php
on line 36
Problems
There are a host of problems with your code as it stands...
Forms posted to PHP use the name attribute in the $_POST superglobal
Therefore you are effectively not submitting anything when you submit your form
Add the name="..." attribute to each of your form elements to fix this
Your if statements are by and large redundant
Not least because you don't post anything as per point 1
You should be using prepared statements for user generated input to protect your database from attack and or corruption
Your code is generally confusing and not laid out very well
I'm not sure what half of your brackets, ifs and function calls are supposed to be doing
The notice you're getting is because you never set $search in your PHP
Solution
N.B
This assumes that all of the code is in the one file [`checkorderstatus.php] and that it submits to itself.
Additional note:
I'm not sure that LIKE '%...% is the best solution here. It appears you're looking for id which, presumably (?) is a number? In which case I would simply user:
WHERE deliverystatus.statusid = SEARCH_ID
The below code follows that premise. If however you are indeed in need of LIKE then you should update the query like:
WHERE deliverystatus.statusid LIKE ?
and update the search term in the code:
$search = "%".$_POST["search"]."%";
Updated HTML form
<form action="checkorderstatus.php" method="post">
<input id="search" name="search" type="text" placeholder="Type here">
<input id="submit" name="submit" type="submit" value="Search">
</form>
Using mysqli
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli ($hn, $un, $pw, $db);
if(isset($_POST["submit"])){
$search = $_POST["search"]; // Prepare the search term
$sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?";
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("i", $search); // Bind search valus as an integer (use "s" if it's a string)
$query->execute(); // Execute the query
$query->store_result(); // Store the result
$query->bind_result($status_description); // Bind "statusdescription" to a varaible
while($query->fetch()){ // Loop through result set
echo $status_description}."<br>"; // Echo each match to a newline
}
}
Using PDO
$pdo = new pdo(
"mysql:host={$hn};dbname={$db}", $un, $pw,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
if(isset($_POST["submit"])){
$search = $_POST["search"]; // Prepare the search term
$sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?";
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$search]); // Execute the query binding search as the parameter
while($result = $query->fetchObject()){ // Loop through result set
echo $result->statusddescription."<br>"; // Echo each match to a newline
}
}

sql message Table 'testowanie.id' doesn't exist

I have a problem with my code, I wanted to do that when I click on a checkbox and then on the acceptation button some information will be inserted into my sql database.
There is my code:
<form action="checkboxes.php" method="post">
<input type="checkbox" name="chk1"> 4K </input>
<input type="submit" name="Submit" value="Submit"></input>
</form>
<?php
/* Database connection */
$sDbHost = 'localhost';
$sDbName = 'testowanie';
$sDbUser = 'root';
$sDbPwd = '';
$Conn = mysql_connect ($sDbHost, $sDbUser, $sDbPwd);
mysql_select_db ($sDbName, $Conn)
$checkbox1 = $_POST['chk1'];
if ($_POST["Submit"]=="Submit") {
for ($i=0; $i<sizeof($checkbox1); $i++) {
$query="INSERT INTO cena (name) VALUES ('".$checkbox1[$i]."')";
mysql_query($query) or die (mysql_error() );
}
echo "Record is inserted";
}
?>
But when I click on the button this don't work and a text appears "Table 'testowanie.cena' doesn't exist" but the problem is that the table really exist.
So if someone can help me it will be great.
The name of the table is monitory, cena is a column in the table. There is no name column. So it should be:
$query="INSERT INTO monitory (cena) VALUES ('".mysql_real_escape_string($checkbox1[$i])."')";
You also need to use mysql_real_escape_string() to prevent SQL-injection. But it would be best if you converted to mysqli or PDO and used prepared queries, since the mysql extension is obsolete and has been removed from the current version of PHP.

have truoble with $mysqli->real_escape_string [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
Hey there i have searched but can not find the answer i am looking for. My form will not post to my database i started getting sql injected so i changed my code around to use $mysqli->real_escape_string but it does not seem to want to still post all i am getting is the error in the code any help would be greatly appreciated.
<form action="" method="post">
<br/>
<input type="text" name="Key" class="dap_text_box" placeholder="Enter Key"/><br/>
<br/>
<input type="text" name="Name" class="dap_text_box" placeholder="Name"/><br/>
<br/>
<input type="text" name="Email" class="dap_text_box" placeholder="Email"/><br/>
<br/>
<input type="text" name="IP_s_" class="dap_text_box" placeholder="Enter IP"/><br/>
<br/>
<input type="submit" name="submit" value="Key Activation" class="sendbutton"/> </form> <hr/> </body> </html>
<?php
if (isset($_POST['submit'])) {
$mysqli = new mysqli("localhost", "root", "rkPJNwe0cI", "key");
// Check
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Set charset for correct escaping
$mysqli->set_charset('utf8');
echo $_SERVER["REMOTE_ADDR"]; // mmm?
$key = $mysqli->real_escape_string($_POST['Key']);
$IP = $mysqli->real_escape_string($_POST['IP']);
$name = $mysqli->real_escape_string($_POST['Name']);
$email = $mysqli->real_escape_string($_POST['Email']);
$IP_s = $mysqli->real_escape_string($_POST["IP_s_"]);
// (ID, Key, Activated, IP, Banned)
$sql = "INSERT INTO keys (ID, Key, Activated, IP, Banned, Name, Email) VALUES ('$ID1', '$key', 1, '$IP', 0, '$name', '$email')";
$sql1 = "SELECT ID, Key, Activated, IP, Name, Email FROM Keys";
$sql = "UPDATE Keys set IP='$IP_s_', Name='$name', Email='$email', Activated='1' WHERE Key='$key'";
if ($mysqli->multi_query($sql) === TRUE) {
echo "Activated";
} else {
echo "Error";
}
$mysqli->close(); }
You have quite a few things wrong from what I can see. Too long for a comment.
You use multi_query() but only have one query defined in $sql. Your insert statement and select statement don't appear to be doing anything, you overwrite the insert statement before you call multi_query().
$ID1 doesn't appear to be defined anywhere for your insert statement.
Why not use prepared statements? So much easier and efficient than trying to escape each individual string.

mysql UPDATE not changing table

I have a made a form to allow for changing a users "UserLevel." However, I cannot seem to get it to work. It just is not changing the UserLevel after submit. I am definitely a PHP newbie. But I have tried researching this for the past hour and cannot seem to make any progress here. Probably something simple I am missing. Any help is appreciated.
The form
<form action="dm/userUpdate.php" method="post">
Username: <input type="text" name="username" value="Username">
<br>
User Level: <input type="number" name="userlevel" value="0">
<input type="Submit" name="submit" value="Change">
</form>
userUpdate.php
<?php
mysql_connect('localhost', 'username', 'password') or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$userlevel = mysql_real_escape_string($_POST["userlevel"]);
$username = mysql_real_escape_string($_POST["username"]);
mysql_query($con,"UPDATE users SET UserLevel= $userlevel WHERE Username ='$username'");
mysql_close($con);
?>
You should escape your variables. Or whatever this is called.
mysql_query("UPDATE users SET UserLevel= '".$userlevel."' WHERE Username ='".$username."'");
Notice i used regular MySQL so no link is required as a parameter. If you are new to MySQL i advice to learn MySQLi right off the bat since it has some handy improvements.
You can't mix mysqli (note the I) and mysql (without an i) functions. The two libraries are NOT interchangeable.
As well, your SQL itself has syntax errors - mysql_real_escape_string() does NOT quote strings for you - it only escapes sql metacharacters, so you'll end up something like
... WHERE Username = Miles O\'Brien
instead of
... WHERE Username = 'Miles O\'Brien'
try this
mysql_query("UPDATE users SET UserLevel= '$userlevel' WHERE Username ='$username'");
mysql_close();
you have no $con variable defined.
Always check for syntax errors. Look at your table name and table fields and make sure they are spelled the same as well as cased.
<?php
$con = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
mysql_select_db("database", $con) or die(mysql_error());
$userlevel = mysql_real_escape_string($_POST["userlevel"], $con);
$username = mysql_real_escape_string($_POST["username"], $con);
mysql_query("UPDATE users SET UserLevel= " . $userlevel . " WHERE Username ='" . $username . "'", $con);
mysql_close($con);
?>
use $con to hold connection link on connected data base and use mysql_query (not mysqli_query it is for MySQLi) and other functtions with that connection variable to work with connected database!

PHP not inserting into tables

I'm having trouble getting a practice signup form to submit data to my database ...
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$name = $email = $password = "";
?>
<form method="post">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
function fix_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
In addition to Ugur's answer, you are mismatching mysqli commands and mysql commands. Here's how to do this in an object oriented fashion:
// create mysqli database object
$mysqli = new mysqli_connect("localhost","username","password","database");
// store your query in a variable. question marks are filled by variables
$sql = "INSERT INTO table_name ('username','password') VALUES (?,?)";
// prepare command uses $sql variable as query
$stmt = mysqli->prepare($sql);
// "ss" means your 2 variables are strings, then you pass your two variables.
$stmt->bind_param("ss",$name,md5($password));
// execute does as it seems, executes the query.
$stmt->execute();
// then print your success message here.
Using prepared statements removes the need to sanitize user input, as harmful input is not substituted into the query directly. For more reading:
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
There are some good tips for using prepared statements in many different scenarios, as well as towards the bottom, there is an explanation on how prepared statements prevent SQL injection.
Missing table name
mysql_query("INSERT INTO ...... ('username','password') VALUES ('$name', md5('$password'))");
You're mixing mysql_* with mysqli_* functions, i.e.: mysqli_connect and mysql_query and you're wrapping your column names in quotes, plus you're missing the table name to insert into.
Try the following, fixed code:
if(isset($_POST['submit'])){
$name = fix_input($_POST["name"]);
$email = fix_input($_POST["email"]);
$password = fix_input($_POST["password"]);
mysqli_connect("localhost","username","password","dbname") or die(mysql_error());
mysqli_query("INSERT INTO `your_table` (`username`,`password`) VALUES ('$name', md5('$password'))");
Print "You've been signed up successfully"; }
You're also using password storage technology that dates back to 1996. MD5 is no longer considered safe to use.
I suggest you look into PHP's password function: http://php.net/password
And if you're having problems with your fix_input() function, you should consider using the mysqli_real_escape_string() function.
then setting up a DB connection while passing a variable to it.
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
and instead of using:
$name = fix_input($_POST["name"]);
use the following:
$name= mysqli_real_escape_string($db, $_POST['name']);
and do the same for the rest.
you don't have table name in your query! also do not use quotation in your column name :)
you have mixed up mysqli and mysql.
Change
mysql_query("INSERT INTO ('username','password') VALUES ('$name', md5('$password'))");
to
mysqli_query("INSERT INTO yoour_table(username',password) VALUES ('$name', md5('$password'))");

Categories