MySQL UPDATE statement works in query but not in PHP code - php

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!

Related

How to fetch a single row from a MySQL DB using MySQLi with PHP? [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am using PHP with MySQli and I want to fetch a single row from the whole SQL DB, which fits in my condition. Just for a note, this is what my current database looks like :
I want to get that single row where, eg. txnid column's value == $txnid (a variable). I tried to build the SQL Query which would fit my requirements, and here's how it looks like : $sql = "SELECT * FROM 'table1' WHERE 'txnid' = " . $txnid;. When I raw-run this Query in phpMyAdmin, it works as expected. I just want to know, after I run the Query in PHP, how to fetch that row's data which came in as response from the Query using MySQLi?
This is the code which I am using to run the Query :
$servername = "localhost";
$username = "XXXXXXXXXXXXXX";
$password = "XXXXXXXXXXXXXX";
$dbname = "XXXXXXXXXXXXXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$txnid = $_GET['id'];
$sql = "SELECT * FROM `testtable1` WHERE `txnid` = " . $txnid;
if ($conn->query($sql) === TRUE) {
echo ""; //what should I do here, if I want to echo the 'date' param of the fetched row?
} else {
echo "Error: " . $sql . "<br>" . $conn->error . "<br>";
}
Add LIMIT 1 to the end of your query to produce a single row of data.
Your method is vulnerable to SQL injection. Use prepared statements to avoid this. Here are some links you can review:
What is SQL injection?
https://en.wikipedia.org/wiki/SQL_injection
https://phpdelusions.net/mysqli_examples/prepared_select
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8mb4");
$txnid= $_GET['name_of_txnid_input_field'];
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `testtable1` WHERE `txnid` = ? LIMIT 1");
$stmt->bind_param("i", $txnid);
// set parameters and execute
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['date_field_you_want_to_display'];
$txnid = $_POST['txnid'];
$sql = "SELECT * FROM tableName WHERE txnid = $txnid";
$result = $conn->query($sql);

Mysql Fetch not working

i really dont know why this code isnt working.. database connection works, the timestamp is written to the database.
But i cant figure out why i get a blank page with this code here (i should see the timestamp as echo).
Anyone an idea about this ?
Thank you!
<?php
$user = "daycounter";
$password = "1234";
$database = "daycounter";
$host = "localhost";
$date = time();
// Create connection
$conn = new mysqli($host, $user, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Error: " . $conn->connect_error);
}
//Insert timestamp in database
$sql = "INSERT INTO datum (datum)
VALUES ('".$date."')";
//check if that worked
if ($conn->query($sql) === TRUE) {
echo "That worked!";
}
//get timestamp from db and display it as echo
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysql_query($select);
while($row = mysql_fetch_object($result))
{
echo "$row->datum";
}
?>
You're using a mysqli DB connection, but calling mysql to do your select. You cannot mix/match the database libraries like that. If you'd had even minimal error checking, you'd have been told that there's no connection to the db:
$result = mysql_query($select) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^
Plus, your select query has syntax errors. 'daycounter' is a string literal - you cannot select FROM a string. 'datum' would be syntactically correct, you can select a string literal from a table, but most like you want:
SELECT datum FROM daycounter
or
SELECT `datum` FROM `daycounter`
Neither of those words are a reserved word, so there's NO need to quote them, but if you're one of those people who insist on quoting ALL identifiers, then they must be quoted with backticks, not single-quotes.
$select = "SELECT 'datum' FROM 'daycounter'";
$result = mysqli_query($conn, $select);
while($row = mysqli_fetch_object($result)) {
echo "$row->datum";
}

migrating mysql to mysqli in ajax environment

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))

PHP Select fields from database where username equals X

im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.

How to insert data into mysql database using oops php5 concepts?

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();

Categories