I am new for PHP5 OOP concept.
Please give some example source code for "How to insert data using oops concept?".I want to use pure php5 concept for this even in the connection.php page also.
I want to improve my knowledge. please any one help me....
I know below the basic concept
insert_db.php
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
connectio.php
<?php
// connect database code
$dbhost ='localhost';
$dbuser = 'tomking';
$dbpass = 'dsfds';
$dbname = 'mydb';
//connectivity of database
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error Connecting to mysql');
mysql_select_db($dbname);
?>
Use Mysqli or PDO for using sql queries instead of directly pass variables to query.
This will cause sql injection when you directly pass variable to query
If you want to pass variable to sql query , you have to use filters for this
filtering-escaping-post-data-from-injection-attacks
PDO Documentation
MySQLi Documentation
And this is all pure PHP5 concept.
$mysqli = new mysqli($hostname, $username, $password, $database_name);
if($mysqli->error)
die($mysqli->error);
$mysqli->query("SET NAMES 'UTF8'");
$query = "INSERT INTO my_table VALUES ('value_1', 'value_2')";
$mysqli->query($query);
if(!$mysql->error)
echo 'do something';
$query = "SELECT * FROM my_table";
$sql = $mysqli->query($query);
if($sql->num_rows > 0) {
while($row = $sql->fetch_assoc()) {
echo $row['field_1'];
}
}
$sql->close();
Related
When I execute the statement in phpmyadmin, it works properly, but when I copy and paste the exact same query into this php file, it doesn't work.
PHP Code:
if($_GET['vote'] == 1) {
echo "if statement ran";
$sql = "UPDATE raids SET attendees = attendees +1 WHERE dateposted = '2017-08-19 16:15:46'";
mysql_query($sql, $link);
}
My link variable does work and the 'if' statement executes. Other SQL statements haven't given me trouble.
Why isn't the php code incrementing 'attendees' when used in the PHP code?
As Milan Chheda said, MySQL is deprecated and is no longer secure. Use PDO or at least MySQLi instead.
MySQLi implementation for your code:
//MySQLi information
$db_host = "localhost";
$db_username = "username";
$db_password = "password";
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die("Error " . mysqli_error());
//select MySQLi dabatase table
$db = mysqli_select_db($connection, "table") or die("Error " . mysqli_error());
if(isset($_GET['vote']) && $_GET['vote'] !== NULL) {
$vote = $_GET['vote'];
if($vote == "1") {
echo "Vote is 1, updating the database";
$sql = mysqli_query($connection, "UPDATE raids SET attendees = attendees + '1' WHERE dateposted = '2017-08-19 16:15:46'");
}
}
I hope this helped you. Good luck!
My code is below, I don't know what is wrong with my code, it says data submitted but not inserted into mysql database when I see in phpmyadmin
<?php
$dbhost = 'localhost';
$dbuser = 'Krishna';
$dbpass = 'xxxx';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
session_start();
if (isset($_POST['submit'])){
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
}
mysqli_select_db($conn, "krishna");
$sql = "INSERT INTO contact_us (name, email, sub, mess)
VALUES ('$_POST[name]','$_POST[email]','$_POST[sub]','$_POST[mess]')";
if(! $sql) {
die('Error: ' . mysqli_error());
}
echo "1 Record Added to Table\n";
echo "<a href='contactForm.html'>Back to main page</a>";
mysqli_close($conn);
?>
First let me start by saying you could do this in an attempt to learn how to use SQL which I also did when I was first learning but then realized ...
This method is subject to SQL injection attacks and should not be used. Directly taking any user input without sanitizing it first is critical mistake that can lead security vulnerabilities.
We now have tools like PDO statements which prepare your SQL for entry into a databases. Please consider using a similar tool which prepares your statements when getting anything from a user.
Users are not to be trusted. In the code below when you bindValue it takes the variable $id and removes anything harmful.
<?php
$stmt = $db->prepare("SELECT * FROM table WHERE id=? AND name=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->bindValue(2, $name, PDO::PARAM_STR);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
See this link for the source of the code above and a tutorial on PDO. There are probably better tutorials out there though.
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
I have a database running on my server with phpmyadmin but I can't connect with it. Here is an example:
$user_name = "xxxxx";
$password = "xxxxx";
$database = "xxxxx";
$host = "db.xxxx.nl";
$db_handle = mysql_connect($host, $user_name, $password);
$db_found = mysql_select_db($database);
But this doesn't seem to work. If I try to insert some values into a table it still stays empty.
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$_FILES["contactBrowse"]["name"]}'
)";
Am I doing something wrong?
I'm going to completely rewrite your code. As you are clearly new to databases within PHP, there is absolutely no reason not to use the new mysqli API.
Your connection should look something like this;
$mysqli = new mysqli($host,$user_name,$password,$database);
if ($mysqli->connect_errno) echo "Failed to connect to MySQL: " . $mysqli->connect_error;
This will create a new database object called $mysqli (or you can call it what you like, such as $db).
You can then prepare your SQL statement and execute it. In the code below, we have 5 parameters that are represented in the SQL as ?, and then we bind the variables to those 5 parameters. The first argument in bind_param tells the API the 5 parameters are 5 strings (hence s x5). For integers, use i;
if($query = $mysqli->prepare("INSERT INTO tbl_forum (title,name,content,lastname,post_image) VALUES (?,?,?,?,?)")) {
$query->bind_param('sssss',$_POST['contactsubject'],$_POST['contactname'],$_POST['contactmessage'],$_POST['contactlastname'],$_FILES["contactBrowse"]["name"]);
$query->execute();
}
else {
echo "Could not prepare SQL: " . $mysqli->error;
}
Assuming all your connection information is correct, this will insert your information into the database as required.
Hope this helps.
I think the last value '{$_FILES["contactBrowse"]["name"]}' has some problem. Try this and get the sql after preparing(echo $sql;) to debug by your self.
$file_name = $_FILES["contactBrowse"]["name"];
$sql = "INSERT INTO tbl_forum
(
title,
name,
content,
lastname,
post_image
)
VALUES
(
'{$_POST['contactsubject']}',
'{$_POST['contactname']}',
'{$_POST['contactmessage']}',
'{$_POST['contactlastname']}',
'{$file_name}'
)";
First i would like to say thank you for letting me ask questions again. I know my previous question was a bit low level of knowledge. Today, I would like to ask if the principle of converting mysql to mysqli in ajax is same with html. Suppose this is my Connect.php
<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "765632";
$dbname = "student";
$link_id = mysqli_connect($host,$dbusername,$dbpassword,$dbname) or die("Error " . mysqli_error($link_id));
?>
and my ajax.php is
<?php
//Connect to MySQL Server
include 'Connect.php';
mysql_connect($host, $dbusername, $dbpassword);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Escape User Input to help prevent SQL Injection
$first_name = mysql_real_escape_string(trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysql_query($query) or die(mysql_error());
//Generate the output
$searchResults = '';
if(!mysql_num_rows($result))
What are the changes should i made to convert it to mysqli without changing its logical scheme.
Did you mean this?
$link_id = mysqli_connect($host, $dbusername, $dbpassword);
//Select Database
mysqli_select_db($link_id, $dbname) or die(mysqli_error($link_id));
// Escape User Input to help prevent SQL Injection
$first_name = mysqli_real_escape_string($link_id, trim($_GET['first_name']));
// Retrieve data from Query
$query = "SELECT student_id, LRN, first_name, last_name, grade, section FROM student_information WHERE first_name LIKE '%{$first_name}%'";
$result = mysqli_query($link_id, $query) or die(mysqli_error($link_id));
//Generate the output
$searchResults = '';
if(!mysqli_num_rows($result))
What is the best way to save a URL or symbols into a MYSQL database.
I'v seen this being used "{$htmlOutputArray[1]}"
and then else where this "$htmlOutputArray[1]"
and some other places do what i'v done below... but which is the best?
So far I have: (example code)
$html = "034251\nhttp://stackoverflow.com/questions/ask"
$htmlOutputArray = explode("\n", "$html");
$htmlOutput = $htmlOutputArray[0];
$postIDOutput = $htmlOutputArray[1];
$con = mysql_connect('localhost', 'user', 'pass') or die('Could not connect: ' . mysql_error());
#echo 'Connected successfully';
mysql_select_db("dbName", $con);
mysql_query("UPDATE tableName SET PostidINT='$postIDOutput', URLofPostTXT='$htmlOutput' WHERE id='$unID'");
mysql_close($con);
First of all you should look into the dangers of SQL injection and how you can prevent it.
Here's both a way you can do this and the safer version.
mysql_select_db("dbName", $con);
$sql = sprintf("UPDATE tableName SET PostidINT=%d, URLofPostTXT='%s' WHERE id=%d",
mysql_real_escape_string($htmlOutputArray[1]),
mysql_real_escape_string($htmlOutputArray[0]),
mysql_real_escape_string($unID));
mysql_query($sql);
mysql_close($con);
What mysql_real_escape_string() is doing is preventing unsafe characters from being entered into your database.
What sprintf() is doing is formatting your string, so for example, only numbers will be entered in the PostidINT and id variables.
I'd vote for prepared statements (and mysqli):
$connection = new mysqli("localhost", "user", "pass", "db");
$statement = $connection->prepare("UPDATE tableName SET PostidINT=?, URLofPostTXT=? WHERE id=?");
$statement->bind_param("i", $postIDOutput);
$statement->bind_param("s", $htmlOutput);
$statement->bind_param("i", $unID);
$statement->execute();