PHP Coding to Connect MYSQL Issues - javascript

I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:
?php
$username = "name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Not connected to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>
Can anyone help me to debug this code?
I will be very thankful to you.

Try this one out. It uses MySQLi with error echoing.
<?php
$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con) {
exit("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($con, "SELECT id, model,year FROM cars");
if (mysqli_error($con)) {
exit("Error: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($result)) {
echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}
mysqli_close($con);

First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.

Related

PHP Javascript Mysql Insert

I am trying to use java-script prompt to insert values into MySQL. I have a html file and a php file.
The html files saved as Test.html:
<button onclick="myFunction()">Create Project</button>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project });
}
}
</script>
The conn.php:
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The conn.php works perfectly and inserts values if I remove the post parameter.
For example, instead of this:
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if i use:
$proj = "NewProject";
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
NewProject gets inserted into the database.
I am not sure if I am missing something in my index.html which is not posting the value in the prompt to php script. I have tried echo $_POST['project']; instead of inserting into MySQL. The echo is missing.
I have run your given code, it runs only i have added the jquery link above script code
Please check this correction,
<button onclick="myFunction()">Create Project</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project },function(response){
console.log(response);
});
}
}
</script>
and also i have added isset() function with $_POST param in conn.php file
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = isset($_POST['project'])?$_POST['project']:'';
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

i am developing a website using php and mysql,in this website

i want to fetch data from my database which is linked to the website,i have created a search box,whenever i enter a particular value in search box,it should display all the related content from the database.i have done the following code,it is not fetching the data from the database,it just shows a blank screen.
<?php
define('db_name','njgh');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
session_start();
$link=mysql_connect(db_host,db_user,db_password);
if(!$link)
{
die('couldnot connetc:'.mysql_error());
}
$db_selected=mysql_select_db(db_name,$link);
if(!$db_selected)
{
die('cant connect to db');
}
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM database WHERE Site_ID = '$value'";
$result = mysql_query($qry);
print_r($result);
mysql_query function return resource ID not your data , use mysql_fetch_array, mysql_fetch_object to get data
$value = ($_POST['searchtext']);
$result = mysql_query("SELECT * FROM database WHERE Site_ID = '$value'");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_* has been removed entirely as of PHP 7.0. Prevent SQL injection and use the mysqli statement class.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "njgh";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['searchtext'];
/* create a prepared statement */
if($stmt = $conn->prepare("SELECT * FROM database WHERE Site_ID =?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $value);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['db_table_field_name'];
}
//or
$row = $result->fetch_assoc();
print_r($row);
} else {
}
/* close statement */
$stmt->close();
}
/* close connection */
$con->close();
?>
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.
Hope this will work for you......
<?php
define('db_name','sports');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
$link=mysqli_connect(db_host,db_user,db_password,db_name);
if(!$link)
{
die('couldnot connect:'.mysql_error());
}
function clean($str) {
$link=mysqli_connect(db_host,db_user,db_password,db_name);
$str = #trim($str);
if(get_magic_quotes_gpc())
$str = stripslashes($str);
return mysqli_real_escape_string($link, $str);
}
if(isset($_POST['searchtext'])){
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM cricket WHERE id = '$value'";
$qrydb = mysqli_query($link, $qry);
while($row=mysqli_fetch_array($qrydb)){
$name = $row['name'];
}
echo $name ;
}
?>
<body>
<form method="post">
<input type="text" name="searchtext">
<input type="submit" name="submit">
</form>
</body>

mysql_fetch_array error at line 6

mysql_fetch_array() expects parameter 1 to be resource, boolean given in
<?php
mysql_connect ("localhost", "cab","a321") or die (mysql_error());
mysql_select_db ("ppwxpjey_mcidb");
$termOrd = $_POST['termOrd'];
$sql = mysql_query("select * from booking where order_no like '%$termOrd%'");
while ($row = mysql_fetch_array($sql)){
echo "<table width='1000' border='2' align='center' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000'><tr><th>ORDER NO</th><th>NAME</th><th>MOBILE</th><th>FROM PLACE</th><th>TO PLACE</th><th>JOURNEY DATE</th><th>JOURNEY TIME</th><th>PERSON</th><th>BOOKING TIME</th></tr>";
echo "<tr><td>".$row["ORDER_NO"]."</td><td>".$row["NAME"]."</td><td>".$row["MOBILE"]."</td><td>".$row["FROM_PLACE"]."</td><td>".$row["TO_PLACE"]."</td><td>".$row["JOURNEY_DATE"]."</td><td>".$row["JOURNEY_TIME"]."</td><td>".$row["PERSON"]."</td><td>".$row["UPDATE_TIME"]."</td></tr>";
echo '<br/>';
}
?>
You've to run the query before passing it in mysql_fetch_array which expects resource as a parameter. So change your code like this,
$sql = mysql_query("select * from booking where order_no like '%$termOrd%'");
$result = mysql_query($query) or die(mysql_error());
// This is where you're getting resource or throwing SQL error.
while ($row = mysql_fetch_array($result)){
// YOUR LOGIC.
}
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed
in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be
used. Source : http://php.net/manual/en/function.mysql-query.php
So update your code as soon as you can.
Use mysqli_* or PDO . mysql_* is deprecated.
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MYSQLi or PDO_MySQL extensions. use prepared statement
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "cab"; //username
$password = "a321"; //password
$mysql_database = "ppwxpjey_mcidb"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$termOrd = "%{$_POST['termOrd']}%";
$stmt = $conn->prepare("select * from booking where order_no like ? ");
$stmt->bind_param('s',$termOrd);
$stmt->execute();
$get_result= $stmt->get_result();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
while($row=$get_result->fetch_assoc())
{
echo "<table width='1000' border='2' align='center' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000'><tr><th>ORDER NO</th><th>NAME</th><th>MOBILE</th><th>FROM PLACE</th><th>TO PLACE</th><th>JOURNEY DATE</th><th>JOURNEY TIME</th><th>PERSON</th><th>BOOKING TIME</th></tr>";
echo "<tr><td>".$row["ORDER_NO"]."</td><td>".$row["NAME"]."</td><td>".$row["MOBILE"]."</td><td>".$row["FROM_PLACE"]."</td><td>".$row["TO_PLACE"]."</td><td>".$row["JOURNEY_DATE"]."</td><td>".$row["JOURNEY_TIME"]."</td><td>".$row["PERSON"]."</td><td>".$row["UPDATE_TIME"]."</td></tr>";
echo '<br/>';
}
}
$stmt->close();
$conn->close();

Jquery ajax call not working if using connection in include file

I can't figure out why jquery ajax post call not working if I used connection on include php file though I'm getting right response from php. Kindly tell me what's the explanation behind this
This is on my DB file
<?php
$host = "mysql2.000webhost.com";
$username = "a212_mt5199";
$password = "secret";
$db = "a211_mydb";
$con = new mysqli ($host, $username, $password, $db);
GLOBAL $con;
if ($con->connect_error) {
die ("Error:" . $con->connect_error);
}
?>
This including the above is not working
<?php
include("db.php");
// set parameters and execute
$myusername=$_POST['name'];
$mypassword=$_POST['pwd'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $con->prepare("SELECT username, password FROM members WHERE username=? and password=?");
$stmt->bind_param("ss", $myusername, $mypassword);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
// Mysql_num_row is counting table row
$count=$stmt->num_rows;
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
echo 'true';
$_SESSION['user_name']= $username;
} else {
echo "Wrong Username or Password";
}
$stmt->close();
$con->close();
?>
This is working
<?php
$host = "mysql2.000webhost.com";
$username = "a212_mt5199";
$password = "secret";
$db = "a211_mydb";
$con = new mysqli ($host, $username, $password, $db);
if ($con->connect_error) {
die ("Error:" . $con->connect_error);
}
// set parameters and execute
$myusername=$_POST['name'];
$mypassword=$_POST['pwd'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $con->prepare("SELECT username, password FROM members WHERE username=? and password=?");
$stmt->bind_param("ss", $myusername, $mypassword);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
// Mysql_num_row is counting table row
$count=$stmt->num_rows;
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
echo 'true';
$_SESSION['user_name']= $username;
} else {
echo "Wrong Username or Password";
}
$stmt->close();
$con->close();
?>
Able to solve issue by using DEFINE variable.

is there a better way of writing folling code in php

I am trying to write a function that will fetch one column from mysql & return it. some how I am not able to write get_hash() function. Further is it safe to use $GLOBALS?
<?php
//Create Database Connection
$dbhost = "localhost";
$dbuser = "developer";
$dbpass = "abc";
$dbname = "abc";
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
//Test Connection`enter code here`
if(mysqli_connect_errno()) {
die("Connection Failed" .
mysqli_connect_error() .
"(" . mysqli_connect_errorno() . ")"
);
}
// Query
$query = "SELECT tweet FROM twc_hashtag";
// Fetch Data
function get_hash() {
if ($result=mysqli_query($GLOBALS['connection'], $GLOBALS['query'])){
while ($row=mysqli_fetch_row($result)){
//echo "<tr>";
//echo "<td>" . $row[0] . "</td>";
//echo "</tr>";
return $row[0];
}
}
//Test Query Error
if(!$result){
die("Database Query Failed" . mysqli_error($GLOBALS['connection']));
}
}
//Close The Connection
mysqli_close($connection);
?>
I need to fetch the data in a different php file & then pass that data to a javascript function. Hence I am going to call get_hash(); from a different php file.

Categories