Basic PDO connection to MySQL - php

I am having trouble testing out this connection, i'm trying to put a test value into the table.
Please take note:
running Xampp V 3.2.2, both apache and mysql are on and the localhost port is also working well.
database and table are setup.
<?php
$dsn = 'mysql:host=localhost:1842;dbname=mesimot;charset=utf8';
$db = new PDO($dsn, 'root', '');
$sql = "INSERT INTO mesima VALUES ('', 'first task','0')";
$count = $db->exec($sql);
if($count){
echo 'updated!' . '<hr>';
}
im running login.php on phpstorm and nothing really happens and I check the table and its still empty.
Anything i'm missing?
Thanks
EDITED:
mesima table is comprised of:
ID (AI)
text varchar 25
and bool tinyint 1

You are trying to connect with a port, use this:
Change,
$dsn = 'mysql:host=localhost:1842;dbname=mesimot;charset=utf8';
To
$dsn = 'mysql:host=localhost;dbname=mesimot;port=1842;charset=utf8';
Notice how I defined the port and how you defined the port?
Additional Information
If the queries first value parameter is an auto incrementing ID, then you can leave it blank.
Edit 1
Change,
INSERT INTO mesima VALUES ('', 'first task','0')
To,
INSERT INTO `mesima` (`mesi`, `done_bool`) VALUES ('first task', '0')

Related

MySQL not using PHP variables properly in Queries, replacing the variables with strings/integers works fine

MySQL is not using the variables as it should. it is not taking any value from them it is incrementing the auto-increment numbers in the MYSQL table, however the row is not saved. I am not given any errors.
I have tried like this:
$sql = "INSERT INTO `tbl_bike` (`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`, `BikeWheel`, `BikeColour`, `BikeSpeed`, `BrakeType`, `FrameGender`, `AgeGroup`, `DistFeatures`)
VALUES (“.$userID.”, “.$PartNo.”, “.$BikeManufacturer.”, “.$BikeModel.”, “.$BikeType.”, “.$BikeWheel.”, “.$BikeColour.”, “.$BikeSpeed.”, “.$BrakeType.”, “.$FrameGender.”, “.$AgeGroup.”, “.$DistFeatures.”)";
I have also tried replacing the " with ', Removing the . and even completely removing the ". Nothing has helped with this issue. When I use this query but remove the variables and instead put string, int etc in the correct places the query will function perfectly and put the results into the table. My variables are normally as follows:
$PartNo = $_POST['ManuPartNo’];
$BikeManufacturer = $_POST['BikeManufacturer’];
$BikeModel = $_POST['BikeModel’];
$BikeType = $_POST['BikeType’];
$BikeWheel = $_POST['BikeWheel’];
$BikeColour = $_POST['BikeColour’];
$BikeSpeed = $_POST['BikeSpeed’];
$BrakeType = $_POST['BrakeType’];
$FrameGender = $_POST['FrameGender’];
$AgeGroup = $_POST['AgeGroup’];
$DistFeatures = $_POST['DistFeatures’];
These variables normally take input from a separate PHP/HTML file with the '$_POST['DistFeatures’];'
I have tried removing the $_POST['DistFeatures’]; from the ends of each of them and just replacing the values with normal string or int values but still nothing helps. I am completely stuck and would appreciate any help with this.
This is all running on a plesk server.
Please stop using deprecated MySQL. I will suggest an answer using PDO. You can use this to frame your other queries using PDO.
// Establish a connection in db.php (or your connection file)
$dbname = "dbname"; // your database name
$username = "root"; // your database username
$password = ""; // your database password or leave blank if none
$dbhost = "localhost";
$dbport = "10832";
$dsn = "mysql:dbname=$dbname;host=$dbhost";
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
// Include db.php on every page where queries are executed and perform queries the following way
// Take Inputs this way (your method is obsolete and will return "Undefined Index" error)
$userId = (!empty($_SESSION['sessionname']))?$_SESSION['sessionname']:null; // If session is empty it will be set to Null else the session value will be set
$PartNo = (!empty($_POST['ManuPartNo']))?$_POST['ManuPartNo']:null; // If post value is empty it will be set to Null else the posted value will be set
$BikeManufacturer = (!empty($_POST['BikeManufacturer']))?$_POST['BikeManufacturer']:null;
$BikeModel = (!empty($_POST['BikeModel']))?$_POST['BikeModel']:null;
$BikeType = (!empty($_POST['BikeType']))?$_POST['BikeType']:null;
$BikeWheel = (!empty($_POST['BikeWheel']))?$_POST['BikeWheel']:null;
// Query like this
$stmt = $pdo->prepare("INSERT INTO(`userID`, `ManuPartNo`, `BikeManufacturer`, `BikeModel`, `BikeType`)VALUES(:uid, :manuptno, :bkman, :bkmodel, :bktype)");
$stmt-> bindValue(':uid', $userId);
$stmt-> bindValue(':manuptno', $PartNo);
$stmt-> bindValue(':bkman', $BikeManufacturer);
$stmt-> bindValue(':bkmodel', $BikeModel);
$stmt-> bindValue(':bktype', $BikeType);
$stmt-> execute();
if($stmt){
echo "Row inserted";
}else{
echo "Error!";
}
See, it's that simple. Use PDO from now on. It's more secured. To try this, just copy the whole code in a blank PHP file and and run it. Your database will receive an entry. Make sure to change your database values here.
You should try this
$sql = "INSERT INTO tbl_bike (userID, ManuPartNo, BikeManufacturer, BikeModel, BikeType, BikeWheel, BikeColour, BikeSpeed, BrakeType, FrameGender, AgeGroup, DistFeatures) VALUES ('$userID', '$PartNo', '$BikeManufacturer', '$BikeModel', '$BikeType', '$BikeWheel', '$BikeColour', '$BikeSpeed', '$BrakeType', '$FrameGender', '$AgeGroup', '$DistFeatures')";
If this doesn't work, enable the null property in sql values. So you can find out where the error originated.

Select Number of Values in Database Column

I have a mySQL table called palettes, and I want to return the number of links in the table. Basically, I want to return the number of values in the link column. (In this case, 6).
I tried using this code, but it didn't work. I'm a front-end dev, with NO knowledge of php or anything..
include "mysql.php";
$select_rows = $mysqli->query("SELECT COUNT(link) FROM palettes");
$rows = mysqli_fetch_array($select_rows);
$total = $rows[0];
echo $total;
The above code should or echoed 6, right? Selecting from column link
This is what my table looks like:
Use the WHERE clause with LIKE 'http%' and change your query to count id's that fit:
First, I'll assume your file 'mysql.php' has a connection to the database somewhere in the file like this:
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
$hostname = 'localhost';
$dbname = 'myDatabaseName';
$username = 'admin';
$password = 'myPassword';
$cxn = mysqli_connect($hostname, $username, $password, $dbname) or DIE('Connection to host is failed, perhaps the service is down!');
?>//End connect.php
Now you can try this:
include 'mysql.php';
$select_rows = mysqli_num_rows(mysqli_query($cxn, "SELECT id FROM palettes WHERE link LIKE 'http%'"));
echo $select_rows; //Should = 6
I would say place NULL in case you don't have the link available:
You can do it by making the Link column to allow NULL as default. You can make use of the COUNT(Link) in that case. This is recommended.
If you have to have empty string instead of NULLs.
select sum(if(Link != "",1,0)) counting from palettes;
Or if you can make sure all the links start with http/https
select sum(if(Link like "http%",1,0)) counting from palettes;

Write to MYSQL table not working

I am trying to write to a MySQL Database / Table with the following code - but for some reason it just won't write! I've changed the "INSERT INTO" line quite a few times, trying different things each time - no luck!!!
The DBsettings.php contains variables with the MySQL connection info - which worked for creating the tables and setting the column types and stuff. For your information, it is running the main code (there are no errors with the user info entered), and echoing "Awesome! No errors!", so I'm not too sure what's not working - the MySQL checking line is saying that I'm able to connect properly... Can someone look over my code?
The PasswordHash.php file contains code for hashing and salting passwords - nothing to see here, got it from another site, no errors at all.
I know I'm not 'cleansing' the MySQL code for more security...
if($error == null){
include('DBsettings.php');
$connect = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL Database! Error: '.mysqli_connect_error();
} else {
include('PasswordHash.php');
$passinfo = explode(':', create_hash($password));
$addinfo = "INSERT INTO {$dbprefix}Users (Email, Displayname, Registered, Rank, Status, Password, Salt) VALUES ('{$email}', '{$displayname}', '{date('Y\/m\/d')}', 9999, 1, '{$passinfo[3]}', '{$passinfo[2]}')";
/* format: algorithm:iterations:salt:hash */
mysqli_query($connect, $addinfo);
mysqli_close($connect);
echo 'Salt: '.$passinfo[2];
echo '<br>Hash: '.$passinfo[3];
echo '<br>Awesome! No Errors!';
}
} else {
echo $error;
}
That's the code in question - I've tried adding;
error_reporting(E_ALL);
ini_set('display_errors', '1');
But all that reveals is undefined localhost errors in my DBsettings.php file - and the file worked when I created the MySQL DB tables, so I don't really have that as a priority.
Thanks!
If you echo your query, you will notice this issue. Following is your final query
INSERT INTO Users (Email, Displayname, Registered, Rank,Status, Password, Salt)
VALUES ('', '', '{date('Y\/m\/d')}', 9999, 1, '', '')
Notice that your date was not interpolated like you expected it to, and i'm sure if you have that field in MySQL set as a datetime field, it wont accept that value {date('Y\/m\/d')}, Move the date function call outside the string.
Plus you are not getting any error after the query execution because you are simply not checking for one. One example how to check for that can be
if (!mysqli_query($connect, $addinfo)) {
printf("Error: %s\n", mysqli_error($connect));
}
I saw your INSERT query contains this '{date('Y/m/d')}' ,maybe the single quotes has conflict,You'd better escaping the date('Y/m/d') statement's single quotes.

Default Field Value to MySQL Database

I'm using a HTML form that captures user input for several fields, some of which can be left blank by the user, one particular field is called 'pasref'. What I would like to be able to do, if at all possible, is if this field is left blank by the user, for the default value to become the text 'Not Allocated' and for this to be saved as part of the record to a mySQL database.
I just admit I'm fairly new to this type of programming and I'm not sure whether this can be done within the mySQL database or whether it needs to be done as part of the php script that saves each record. I just wondered whether it would be at all possible please that someone could show me what I need to do?
I've included my PHP script below if it helps.
<?php
require("phpfile.php");
// Gets data from URL parameters
$userid = $_GET['userid'];
$locationid = $_GET['locationid'];
$pasref = $_GET['pasref'];
$additionalcomments = $_GET['additionalcomments'];
// Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO finds " .
" (userid, locationid, pasref, additionalcomments ) " .
" VALUES ('%s', '%s', '%s', '%s');",
mysql_real_escape_string($userid),
mysql_real_escape_string($locationid),
mysql_real_escape_string($pasref),
mysql_real_escape_string($additionalcomments));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
You can set the default value on the column of mysql. You need to execute a query something like this:
ALTER TABLE finds MODIFY pasref varchar(100) default 'Not Allocated';
Change varchar(100) to whatever length it should be for your field.
Alternatively you could just set it in php:
if( empty($_GET['pasref']) ) {
$pasref = 'Not Allocated';
}
else {
$pasref = $_GET['pasref'];
}
Or finally you could put it as a default value in your form. Though the user would need to clear it if they want something else:
<input type="text" name="pasref" value="Not Allocated" />
Finally just to note in your PHP you need to escape your inputs to the database with mysql_real_escape_string or use PDO with placeholders. As is you have a SQL injection vulnerability.
It's also better to use POST. Change the form method to POST in your HTML and reference $_POST instead of $_GET
This can be solved by changing the column properties in the mysql database and setting the pasref column to not null and setting a default value.
Easily done if you can access the db using phpmyadmin
ALTER TABLE finds ALTER pasref SET DEFAULT = 'Not Allocated'
So when a new row is inserted with no value for column_name, Not Allocated with be used. It can also be done pretty easily with an interface like phpMyAdmin or MySQL Workbench if you have access to those tools.
Now all you have to do is check if pasref is empty in your PHP code and make sure you don't insert anything (an empty string "" is something) when it is the case.
you can just change the line
$pasref = $_GET['pasref'];
to
$pasref = $_GET['pasref'] == '' ? 'Not Allocated' : $_GET['pasref'];
Use this:
$query = " UPDATE $tabla SET fecha_ultimo_cambio=DEFAULT WHERE id in ($id) ";

my insert query is working in my localhost but not in web server

I am using flex builder 3 to insert into mysql database using php and everything is working perfectly in my localhost, the problem is when I deploy the project in the web server and run it, it connect to the database but i can't insert data ( it shows nothing when i insert data )
another stupid thing is in another piece of code for retrieving (select) data that works good on both my localhost and web server.
here is the php code:
<?php
$host = "******";
$user = "******";
$pass = "******";
$database = "******";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$nickname = $_POST['nickname'];
$steam = $_POST['steam'];
$c1 = $_POST['c1'];
$c2 = $_POST['c2'];
$c3 = $_POST['c3'];
$results = mysql_query("INSERT INTO `phantom`.`members` (`TF2_Nickname` ,`Steam_User_Name`,
`class1` ,`class2` ,`class3` ,`time`) VALUES ($nickname, $steam, $c1, $c2, $c3,NOW())");
?>
You need to declare the values as strings in your MySQL query as well:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('$nickname', '$steam', '$c1', '$c2', '$c3', NOW())"
And you should also prepare them in some way to avoid that they are mistakenly treated as SQL command (see SQL Injection). PHP has the mysql_real_escape_string function to do that:
"INSERT INTO `phantom`.`members` (`TF2_Nickname`, `Steam_User_Name`, `class1`, `class2`, `class3`, `time`)
VALUES ('".mysql_real_escape_string($nickname)."', '".mysql_real_escape_string($steam)."', '".mysql_real_escape_string($c1)."', '".mysql_real_escape_string($c2)."', '".mysql_real_escape_string($c3)."', NOW())"
Insert into requires either user right or admin right. Check if by chance You didnt modify somewhere in the code these rights, e.g., You changed by hand the name of your admin... If it works the select it is because selecting doesnt need so many rights. Even non user status can retrieve info through select but insert needs special rights. You know your code so think about this difference

Categories