I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }
I was trying insert values simultaneously into MySQL database using mysqli_multi_query but it's not executing and going to if part showing alert message stating Record Insertion Failed.
Below is my PHP code with query
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
$sql_tableone = "INSERT into inverterlog (`id`,`timestamp`,`irradiance`,`ambienttemp`,`photovoltaictemp`,`pv1voltage`,`pv2voltage`,`pv3voltage`,`pv1current`,`pv2current`,`pv3current`,`pv1power`,`pv2power`,`pv3power`,`pv1energy`,`pv2energy`,`pv3energy`,`gridvoltagegv1`,`gridvoltagegv2`,`gridvoltagegv3`,`gridcurrentgc1`,`gridcurrentgc2`,`gridcurrentgc3`,`gridpowergp1`,`gridpowergp2`,`gridpowergp3`,`sumofapparentpower`,`gridpowertotal`,`gridenergyge1`,`gridenergyge2`,`gridenergyge3`,`socounter`,`gridcurrentdcgc1`,`gridcurrentdcgc2`,`gridcurrentdcgc3`,`gridresidualcurrent`,`gridfrequencymean`,`dcbusupper`,`dcbuslower`,`temppower`,`tempaux`,`tempctrl`,`temppower1`,`temppowerboost`,`apparentpowerap1`,`apparentpowerap2`,`apparentpowerap3`,`sovalue`,`reactivepowerrp1`,`reactivepowerrp2`,`reactivepowerrp3`,`opmode`,`latestevent`,`pla`,`reactivepowermode`,`overexcitedunderexcited`,`reactivepowerabs`,`inverter`)
values('','$newDate','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]','$emapData[8]','$emapData[9]','$emapData[10]','$emapData[11]','$emapData[12]','$emapData[13]','$emapData[14]','$emapData[15]','$emapData[16]','$emapData[17]','$emapData[18]','$emapData[19]','$emapData[20]','$emapData[21]','$emapData[22]','$emapData[23]','$emapData[24]','$emapData[25]','$emapData[26]','$emapData[27]','$emapData[28]','$emapData[29]','$emapData[30]','$emapData[31]','$emapData[32]','$emapData[33]','$emapData[34]','$emapData[35]','$emapData[36]','$emapData[37]','$emapData[38]','$emapData[39]','$emapData[40]','$emapData[41]','$emapData[42]','$emapData[43]','$emapData[44]','$emapData[45]','$emapData[46]','$emapData[47]','$emapData[48]','$emapData[49]','$emapData[50]','$emapData[51]','$emapData[52]','$emapData[53]','$emapData[54]','$emapData[55]','$inverter')";
$sql_tabletwo = "INSERT into data (`id`,`timestamp`,`gridpowertotal`,`inverter`) values ('','$newDate','$emapData[26]','$inverter')";
$sql= $sql_tableone.";".$sql_tabletwo;
$result = mysqli_multi_query( $con,$sql);
if (! $result ) {
echo "<script type=\"text/javascript\">
alert(\"multi query Record Insertion Failed.\");
</script>";
}
fclose($file);
}
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"four.php\"
/</script>";
//close of connection
mysqli_close($con);
}
}
If the id column is auto-incremented in the tables, then omit the column (and the empty value) from your query. Alternatively, you can use NULL (not quoted) if you are going to mention the column in your query.
Many, many people struggle to find the errors with their mysqli_multi_query() code block because it is not set up to properly output affected rows and errors.
I recommend having a look at a general purpose code block that will help to isolate troublesome queries, and read this answer.
It also looks like you are while-looping mysqli_multi_query()'s two queries. For efficiency, I recommend building up the full array of queries, finishing the loop, then calling mysqli_multi_query() only once.
p.s. Do any of your insert values have quotes in them? Prepared statements would help with that issue. Use the code block from my link and check the error message.
UPDATE: Here is my spoon-fed answer (Of course, I didn't actually test it before posting):
// I assume $newdate is not user declared and considered safe.
// I am using NULL for your auto-incremented primary key `id`.
// If you want to be assured that each pair has an identical `id`, perhaps use LAST_INSERT_ID() on second query of pair.
// establish variables for future use
$inverterlog_sql="INSERT INTO `inverterlog` (`id`,`timestamp`,`irradiance`,`ambienttemp`,`photovoltaictemp`,`pv1voltage`,`pv2voltage`,`pv3voltage`,`pv1current`,`pv2current`,`pv3current`,`pv1power`,`pv2power`,`pv3power`,`pv1energy`,`pv2energy`,`pv3energy`,`gridvoltagegv1`,`gridvoltagegv2`,`gridvoltagegv3`,`gridcurrentgc1`,`gridcurrentgc2`,`gridcurrentgc3`,`gridpowergp1`,`gridpowergp2`,`gridpowergp3`,`sumofapparentpower`,`gridpowertotal`,`gridenergyge1`,`gridenergyge2`,`gridenergyge3`,`socounter`,`gridcurrentdcgc1`,`gridcurrentdcgc2`,`gridcurrentdcgc3`,`gridresidualcurrent`,`gridfrequencymean`,`dcbusupper`,`dcbuslower`,`temppower`,`tempaux`,`tempctrl`,`temppower1`,`temppowerboost`,`apparentpowerap1`,`apparentpowerap2`,`apparentpowerap3`,`sovalue`,`reactivepowerrp1`,`reactivepowerrp2`,`reactivepowerrp3`,`opmode`,`latestevent`,`pla`,`reactivepowermode`,`overexcitedunderexcited`,`reactivepowerabs`,`inverter`) VALUES (NULL,$newdate";
$data_sql="INSERT INTO `data` (`id`,`timestamp`,`gridpowertotal`,`inverter`) VALUES (NULL,'$newDate'";
$tally=0;
$x=0;
// build all queries
while(($emapData=fgetcsv($file,10000,","))!==false){
++$x;
$sql[$x]=$inverterlog_sql; // start first query of pair
for($i=1; $i<56; ++$i){
$sql[$x].=",'".mysqli_real_escape_string($con,$emapData[$i])."'";
}
$sql[$x].=",'".mysqli_real_escape_string($con,$inverter)."');"; // end first query of pair
$sql[$x].="$data_sql,'".mysqli_real_escape_string($con,$emapData[26])."','".mysqli_real_escape_string($con,$inverter)."')"; // whole second query of pair
fclose($file);
}
// run all queries
if(mysqli_multi_query($con,implode(';',$sql)){
do{
$tally+=mysqli_affected_rows($con);
} while(mysqli_more_results($con) && mysqli_next_result($con));
}
// assess the outcome
if($error_mess=mysqli_error($con)){
echo "<script type=\"text/javascript\">alert(\"Syntax Error: $error_mess\");</script>";
}elseif($tally!=$x*2){ // I don't expect this to be true for your case
echo "<script type=\"text/javascript\">alert(\"Logic Error: Only $tally row",($tally!=1?"s":"")," inserted\");</script>";
}else{
echo "<script type=\"text/javascript\">alert(\"CSV File has been successfully Imported.\"); window.location = \"four.php\"/</script>";
}
mysqli_close($con);
So I am trying to echo out how many rows there are in a table with a COUNT command, but I purposely have no rows in the table right now to test the if statement, and it is not working, but worst, it makes the rest of the site not work(the page pops up but no text or numbers show up on it), when I added a row to the table, it worked fine, no rows = no work. Here is the piece of the code that doesn't work. Any and all help is highly appreciated.
$query1 = mysql_query("
SELECT *, COUNT(1) AS `numberofrows` FROM
`table1` WHERE `user`='$username' GROUP BY `firstname`,`lastname`
");
$numberofrowsbase = 0;
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
$enteries1 = $enteries1;
}else{
$enteries1 = $numberofrowsbase;
}
echo enteries1;
}
Seems you have over complicated everything. Some good advise from worldofjr you should take onboard but simplest way to get total rows from a table is:
SELECT COUNT(*) as numberofrows FROM table1;
There are several other unnecessary lines here and the logic is all bonkers. There is really no need to do
$enteries1 = $enteries1;
This achieved nothing.
Do this instead:
while($row = mysql_fetch_assoc($query1))
{
if(isset($row['numberofrows']))
{
echo $row['numberofrows'];
}
}
Maybe against my better judgement, I'm going to try and give you an answer. There's so many problems with this code ...
Do Not Use mysql_
The mysql_ extension is depreciated. You should use either mysqli_ or PDO instead. I'm going to use mysqli_ here.
SQL Injection
Your code is wide open to SQL injection where others can really mess up your database. Read How can I prevent SQL injection in PHP? for more information.
The Code
You don't need to count the rows with a SQL function, especially if you want to do something else with the data you're getting with the query (which I assume you are since you're getting a count on top of all the columns.
In PHP, you can get how many rows are in a result set using a built in function.
So all those things together. You should use something like this;
// Connect to the database
$mysqli = new mysqli($host,$user,$pass,$database); // fill in your connection details
if ($mysqli->connect_errno) echo "Error - Failed to connect to database: " . $mysqli->connect_error;
if($query = $mysqli->prepare("SELECT * FROM `table1` WHERE `user`=?")) {
$query->bind_param('s',$username);
$query->execute();
$result = $query->get_result();
echo $result->num_rows;
}
else {
echo "Could not prepare query: ". $mysqli->error;
}
The number of rows in the result is now saved to the variable $result->num_rows, so you can use just echo this if you want, like I have in the code above. You can then go onto using any rows you got from the database. For example;
while($row = $result->fetch_assoc()) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo "$firstname $lastname";
}
Hope this helps.
We have a table vehicle and a simple php form. Before inserting data I do check if the vehicle registration number exist but some client pc could enter duplicate entries. Below is the code snippet. What else could be causing this ?
$vehicleRegistrationNumber=$_POST['vehicleRegistrationNumber'];
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."'";
$result1 = mysqli_query($link,$selectQuery1);
$row1 = mysqli_fetch_array($result1, MYSQL_ASSOC);
$n1 = mysqli_num_rows($result1);
if($n1 > 0) {
$status="<span class=\"statusFailed\">: Vehicle ".$vehicleRegistrationNumber." Already Exist.</span>";
}
else {
//insert codes
}
First of all your code is vulnerable to SQL injection. This check can be bypassed by submitting something like XYZ0001' AND 1='0 or even more malicious values. To prevent this, use prepared statements and param binding instead of string concatenation.
Other possibility is simply user mistake, for example trailing space ("XYZ001" != "XYZ0001 ") that is hard to spot on the first glance ad records in DB. Before checking its existence in DB you should check with PHP if submitted value includes only allowed chars and is free from common mistakes.
try this with group by
$selectQuery1 ="Select vehicleRegistrationNumber From Vehicle Where vehicleRegistrationNumber='".$vehicleRegistrationNumber."' GROUP BY vehicleRegistrationNumber";
The best way is to handle it on the SQL side. Just define the field as UNIQUE INDEX.
Now when trying to insert a duplicate index an error will be thrown and you can catch it like this:
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
Like this you can avoid the select query before every insert query. Just handle the error as you want.
I'm trying to create an update function in PHP but the records don't seem to be changing as per the update. I've created a JSON object to hold the values being passed over to this file and according to the Firebug Lite console I've running these values are outputted just fine so it's prob something wrong with the sql side. Can anyone spot a problem? I'd appreciate the help!
<?php
$var1 = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$name = $jsonObject->{'name'}; // Get name from object
$desc = $jsonObject->{'desc'}; // Get desc from object
$did = $jsonObject->{'did'};// Get id object
mysql_connect("localhost","root",""); // Conect to mysql, first parameter is location, second is mysql username and a third one is a mysql password
#mysql_select_db("findadeal") or die( "Unable to select database"); // Connect to database called test
$query = "UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}";
$add = mysql_query($query);
$num = mysql_num_rows($add);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
I believe you are misusing the curly braces. The single quote should go on the outside of them.:
"UPDATE deal SET dname = {'$name'}, desc={'$desc'} WHERE dealid = {'$did'}"
Becomes
"UPDATE deal SET dname = '{$name}', desc='{$desc}' WHERE dealid = '{$did}'"
On a side note, using any mysql_* functions isn't really good security-wise. I would recommend looking into php's mysqli or pdo extensions.
You need to escape reserved words in MySQL like desc with backticks
UPDATE deal
SET dname = {'$name'}, `desc`= {'$desc'} ....
^----^--------------------------here
you need to use mysql_affected_rows() after update not mysql_num_rows